I appeared for an interview lately. The interviewer asked me the problem. I have 2 tables:
First table is Location
like this:
ID | City
---+-----------
1 | Mumbai
2 | Delhi
3 | Bangalore
Second table is Item
like this:
Item | Location_id
-----+-------------
A | 1,2
B | 2,3
C | 1,2,3
Now we want the output as below
Item | Location
-----+-------------------------
A | Mumbai,Delhi
B | Delhi,Bangalore
C | Mumbai,Delhi,Bangalore
Please help me write the query.
答案 0 :(得分:0)
You want to STUFF
all matching results into one column:
SELECT i.item,
STUFF((SELECT ',' + l.city
FROM location l
WHERE CHARINDEX(cast(l.id AS VARCHAR(4)),i.location_id)>0
FOR XML PATH ('')), 1, 1, '')
AS Location
FROM item i;
CHARINDEX
finds the first instance of a substring in a string, in this case it finds that you have the number 1 for Mumbai, 2 for Dehli etc in your string of location_id.
STUFF
combines your results into a single result.
UPDATE -
As pointed out by Rajneesh, this only works because your IDs are single digit. String splitting is probably the best way to handle the possibility of such IDs. That can still be done within this one query, without the need for a temp table.
SELECT i.item,
STUFF((SELECT ',' + l.city
FROM location l
WHERE l.id IN (select value from STRING_SPLIT(i.location_id, ','))
FOR XML PATH ('')), 1, 1, '')
AS Location
FROM item i;
答案 1 :(得分:0)
您可以使用以下查询。字符串拆分适用于SQL Server 2016及更高版本。
Select * into #temp
from #location l
join (
select item,value from #item
CROSS APPLY STRING_SPLIT(location_id, ',')
) A on l.id=a.value
select
item,
stuff((
select ',' + u.city
from #temp u
where u.item = A.item
for xml path('')
),1,1,'') as List
from #temp A
group
by item
Drop table #temp