Is there any way to change a SQL query that would normally return multiple rows with the same values into a single row as comma separated?
Table1
------
Col1
------
Sci-Fi
Action
Crime
Table2
------------
Col1 | Col2
------------
1 | Action
1 | Sci-Fi
2 | Crime
2 | Action
2 | Sci-Fi
And I need a query that results like this: (Table1 and Table2 combined)
----------------------------
Col1 | Col2
----------------------------
1 | Action, Sci-Fi
2 | Crime, Action, Sci-Fi
SELECT MG.movie_id , STUFF(( SELECT ',' + G.genre_name FROM Movie_Genre AS G WHERE G.movie_id = MG.movie_id ORDER BY G.genre_name FOR XML PATH('') ), 1, 1, '') AS Genres FROM Movie_Genre AS MG GROUP BY MG.movie_id
感谢这个职位的疯狂真棒STUFF表达。
You can use STUFF function to combine multiple row as comma separated.
SELECT ID, col2 =
stuff((
SELECT ','+ [col2] FROM t WHERE Id = t1.Id FOR XML PATH('')
),1,1,'')
FROM (SELECT DISTINCT ID FROM t ) t1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.