sqlserver中group by 与 concat 的使用
以下内容是基于这样一种查询需求:
1. 表的数据如下:
表名: benefit_service_code
benefit_id service_code
4676 SURG
4676 PV-OUT
4676 XL
4676 SPVOUT
4676 PREMED
4676 BON/HE
4681 XL
4682 XL
2. 期望查询的结果如下:
id code
4676 SURG, PV-OUT, XL, SPVOUT, PREMED, BON/HE
4677 SURG
4678 SURG
4679 PV-OUT
4680 PV-OUT
4681 XL
4682 XL
即根据 相同 的id 将 code 用逗号(,) 连接起来.
这问题有多种方式可以解决, 这儿使用 临时 表 + XML 实现, 具体如下:
CREATE TABLE #benefit_code (id INT, code nvarchar(255));
insert into #benefit_code(id,code)
SELECT
benefit_id,
STUFF((
SELECT ', ' + CAST(service_code AS VARCHAR(MAX))
FROM benefit_service_code
WHERE (benefit_id = Results.benefit_id)
FOR XML PATH (''))
,1,2,'') AS NameValues
FROM benefit_service_code Results
GROUP BY benefit_id;
select * from #benefit_code;
drop table #benefit_code;
参考: http://stackoverflow.com/questions/273238/how-to-use-group-by-to-concatenate-strings-in-sql-server