日期:2014-05-17 浏览次数:20620 次
----------------------------------------------------------------
-- 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'<