Reputation: 523
I have a 2 tables in SQL Server in which there are multiple locations for a name, all I need to do is to club locations into one cell for that names.
Table 1
Name
H
I
J
Table 2
Name Location
H Delhi
H Mumbai
H Hyderabad
I Chennai
I Delhi
Now after applying join the result should be as follows
Name Location
H Delhi, Mumbai, Hyderabad
I Chennai, Delhi
Please help me out in this asap.
Upvotes: 0
Views: 2731
Reputation: 337
Hi I just realised that u need two tables just a few alteration in the code, check the code below
Create table #temp1
(
Name varchar(10)
)
Create table #temp2
(
Name varchar(10),
Location varchar(100)
)
Insert into #temp1
values ('h' ),('I' )
Insert into #temp2
values ('h','delhi'),
('h','Mumbai'),
('h','Hyderabad'),
('I','Chennai'),
('I','Delhi')
Select *from #temp1
Select *from #temp2
select t.Name,
STUFF(( SELECT ', ' +te.Location
FROM #temp2 te
WHERE T.Name = te.Name
FOR XML PATH ('')
),1,1,'') as Location
from #temp1 t
group by t.Name
DROP TABLE #temp1;
DROP TABLE #temp2;
Upvotes: 0
Reputation: 337
Check this code , You can use the xml path for concatenation purpose
DROP TABLE #temp;
Create table #temp
(
Name varchar(10),
Location varchar(100)
)
Insert into #temp
values ('h','delhi'),
('h','Mumbai'),
('h','Hyderabad'),
('I','Chennai'),
('I','Delhi')
select t.Name,
STUFF(( SELECT ', ' +te.Location
FROM #temp te
WHERE T.Name = te.Name
FOR XML PATH ('')
),1,1,'') as Location
from #temp t
group by t.Name
Result Set
Name Location
h delhi, Mumbai, Hyderabad
I Chennai, Delhi
Upvotes: 2