简体   繁体   English

使用2个表将多行汇总为单行

[英]Rolling up multiple rows into single row using 2 tables

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? 有什么方法可以更改通常以逗号分隔将具有相同值的多行返回到一行的SQL查询吗?

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) 我需要一个查询,其结果是这样的:(表1和表2合并)

----------------------------
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. 您可以使用STUFF函数将多行合并为逗号分隔。

Sample SQl Fiddle 样本SQl小提琴

SELECT ID, col2 =
            stuff((
                   SELECT ','+ [col2] FROM t WHERE Id = t1.Id FOR XML PATH('')
                  ),1,1,'') 
FROM (SELECT DISTINCT ID FROM t ) t1

Refer Here for More 请参考这里了解更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM