sql server group分组查询拼接字符串
数据库表
ID | Num | No |
---|---|---|
1 | 50 | A |
1 | 50 | B |
2 | 10 | B |
2 | 10 | C |
查询语句
SELECT
ID,
SUM(Num) sum_num,
STUFF((select ',' + NO from Info i2 where i2.ID = i.ID for xml path('')),1,1,'')
FROM
Info i
GROUP BY
ID
2017以上版本sql
SELECT
ID,
SUM(Num) sum_num,
STRING_AGG(name , ',')
FROM
Info i
GROUP BY
ID