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

时间:2023-01-21 15:14:10

鉴于群里很多同事在问这个问题,我简单写个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

 PS: 由于T2.name中的值会被转换成XML存放,因此会导致某些字符被转义 如<>