日期:2014-05-17 浏览次数:20470 次
SELECT name ,
[id] = STUFF(( SELECT ',' + CONVERT(VARCHAR, id)
FROM tb t
WHERE name = tb.name
FOR
XML PATH('')
), 1, 1, '')
FROM tb
GROUP BY name
select [name],[id]=stuff(( select ',' +rtrim(id) from tb t2 where t1.[name]=t2.[name] for xml path('')), 1, 1, '')from tb t1
group by [name]
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-03-04 16:22:45
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)
-- Jun 17 2011 00:54:03
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1, v.721)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([id] int,[NAME] varchar(6))
insert [huang]
select 1,'你好' union all
select 2,'你好' union all
select 3,'你好' union all
select 4,'我好' union all
select 5,'大家好'
--------------开始查询--------------------------
SELECT a.name ,
STUFF(( SELECT ',' + CONVERT(VARCHAR(10),id)
FROM [huang] b
WHERE b.name = a.name
FOR
XML PATH('')
), 1, 1, '') 'id'
FROM [huang] a
GROUP BY a.name