日期:2014-05-17 浏览次数:20520 次
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-03-29 15:43:43
-- 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)
--
----------------------------
--> 测试数据:[dt]
if object_id('[dt]') is not null drop table [dt]
go
create table [dt]([id] int,[t] varchar(10))
insert [dt]
select 1,'我的' union all
select 1,'他的' union all
select 1,'你的' union all
select 1,'有的' union all
select 1,'没的是的' union all
select 2,'好的' union all
select 2,'坏的' union all
select 2,'反正是你的' union all
select 2,'也不是我的' union all
select 2,'有你的' union all
select 3,'小样' union all
select 3,'小小样' union all
select 3,'来小样' union all
select 4,'不要了' union all
select 4,'送你的' union all
select 4,'送他的' union all
select 4,'送不送' union all
select 4,'不送算了'
--------------开始查询--------------------------
SELECT a.id ,
STUFF(( SELECT ',' + t
FROM [dt] b
WHERE b.id = a.id
FOR
XML PATH('')
), 1, 1, '') 't'
FROM [dt] a
GROUP BY a.id
----------------结果----------------------------
/*
id t
----------- ----------------------------------------------------------------------------------------------------------------