使用2个表将多行卷成单行

时间:2015-06-02 18:51:59

标签: sql sql-server

有没有办法更改一个SQL查询,该查询通常会将具有相同值的多行返回到以逗号分隔的单行中?

Table1
------
Col1
------
Sci-Fi
Action
Crime

Table2
------------
Col1 | Col2
------------
1    | Action
1    | Sci-Fi
2    | Crime
2    | Action
2    | Sci-Fi

我需要一个结果如下的查询: (表1和表2合并)

----------------------------
Col1 |  Col2
----------------------------
1    | Action, Sci-Fi
2    | Crime, Action, Sci-Fi

2 个答案:

答案 0 :(得分:3)

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

感谢this post疯狂的令人敬畏的STUFF表达。

答案 1 :(得分:1)

您可以使用STUFF函数将多行组合为逗号分隔。

Sample SQl Fiddle

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