按SQL Server分组(显示所选组中的所有元素)

时间:2017-01-03 02:17:26

标签: mysql sql sql-server group-by

我对查询感到困惑,我在SQL Server查询中显示表时遇到问题。希望我的截图清楚地显示我的问题:

this is my expectation

1 个答案:

答案 0 :(得分:1)

    ;WITH tb(id,id_ang,bulan)AS(
       SELECT 1,1,1 UNION
       SELECT 2,2,1 UNION
       SELECT 3,1,13 UNION
       SELECT 4,1,2
    )
    SELECT id_ang,STUFF(c.bulans,1,1,'') AS bulans FROM tb 
    OUTER APPLY(SELECT ','+LTRIM(bulan) FROM tb AS tt WHERE tt.id_ang=tb.id_ang ORDER BY ID FOR XML PATH('') ) c(bulans)
    GROUP BY id_ang,c.bulans
id_ang  bulans
1   1,13,2
2   1