日期:2014-05-17 浏览次数:20436 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-01-21 16:57:12
-- 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: )
--
----------------------------------------------------------------
--> 测试数据:[t1]
if object_id('[t1]') is not null drop table [t1]
go
create table [t1]([id] int,[desc] varchar(3))
insert [t1]
select 1,'aaa' union all
select 1,'bbb' union all
select 1,'ccc' union all
select 2,'xxx' union all
select 2,'yyy'
--------------开始查询--------------------------
select a.id,
stuff((select ','+[desc] from [t1] b
where b.id=a.id
for xml path('')),1,1,'') 'desc'
from [t1] a
group by a.id
----------------结果----------------------------
/*
id desc
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 aaa,bbb,ccc
2 xxx,yyy
*/
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-01-21 16:57:12
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23: