I have two tables named Animals and Details respectively:
ID Name Strength
1 Alice 20
2 Bob 30
3 Alex 45
ID Zone
1 Z1
1 Z2
2 Z1
2 Z2
3 Z1
3 Z2
3 Z3
I want to form groups according to names like the one shown below(name and their distinct zones):
Name Zone
Alice Z1,Z2
Bob Z1,Z2
Alex Z1,Z2,Z3
For that I have written following MSSQL code but it is not giving correct output for Alex:
with cte as
(
select a.name, d.zone from Details d join Animals a on a.ID=d.ID
)
select a1.name, concat(a1.zone+',', a2.zone) from cte a1, cte a2 where a1.name=a2.name and a1.zone<>a2.zone
What changes are required in this code? Please help!