22,209
社区成员
发帖
与我相关
我的任务
分享
----------------------------------------------------------------
-- 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
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 我的,他的,你的,有的,没的是的
2 好的,坏的,反正是你的,也不是我的,有你的
3 小样,小小样,来小样
4 不要了,送你的,送他的,送不送,不送算了
*/