如何合并输出
有记录如下
ID NAME VALUE
1 ZH T1
2 ZH T2
3 ZH T3
4 DZ T1
4 DZ T2
如何输出为
NAME VALUE
ZH T1,T2,T3
DZ T1,T2
[解决办法]
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-12-09 20:46:39
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
--Dec 28 2012 20:23:12
--Copyright (c) Microsoft Corporation
--Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([ID] int,[NAME] varchar(2),[VALUE] varchar(2))
insert [huang]
select 1,'ZH','T1' union all
select 2,'ZH','T2' union all
select 3,'ZH','T3' union all
select 4,'DZ','T1' union all
select 4,'DZ','T2'
--------------开始查询--------------------------
select a.[NAME],
stuff((select ','+[VALUE] from [huang] b
where b.[NAME]=a.[NAME]
for xml path('')),1,1,'') 'VALUE'
from [huang] a
group by a.[NAME]
----------------结果----------------------------
/*
NAME VALUE
---- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
DZ T1,T2
ZH T1,T2,T3
*/
create table #tab([ID] int,[NAME] varchar(2),[VALUE] varchar(2))
insert #tab
select 1,'ZH','T1' union all
select 2,'ZH','T2' union all
select 3,'ZH','T3' union all
select 4,'DZ','T1' union all
select 4,'DZ','T2'
select distinct name,
(select stuff((
select ','+value from #tab b where a.name=b.name for xml path('')),1,1,''))value
from #tab a
name value
---- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
DZ T1,T2
ZH T1,T2,T3
(2 row(s) affected)