首页 > 代码库 > TSQL--按某字段列分组,在将各组中某列合并成一行

TSQL--按某字段列分组,在将各组中某列合并成一行

鉴于群里很多同事在问这个问题,我简单写个Demo,希望对初学者有帮助!

 

无真相,无解说,不解释,直接上Code!

--==================================================
--示例代码,仅供参考
--按照object_id分组,将同一组的name列的值合并在一起
SELECT  OBJECT_NAME(T1.object_id) AS ObjectName ,
        ( SELECT    T2.name + ,
          FROM      sys.all_columns T2
          WHERE     T2.object_id = T1.object_id
        FOR
          XML PATH(‘‘)
        ) AS ColNames
FROM    sys.all_columns T1
GROUP BY T1.object_id