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 
posted @ 2023-03-02 14:40  Dark华  阅读(230)  评论(0编辑  收藏  举报