日期:2014-05-17  浏览次数:20455 次

列合并成字符串
数据表dt:
1 我的
1 他的
1 你的
1 有的
1 没的是的
2 好的
2 坏的
2 反正是你的
2 也不是我的
2 有你的
3 小样
3 小小样
3 来小样
4 不要了
4 送你的
4 送他的
4 送不送
4 不送算了

想得到:
1   我的,他的,你的,有的,没的是的
2   好的,坏的,反正是你的,也不是我的,有你的
3   小样,小小样,来小样
4   不要了,送你的,送他的,送不送,不送算了

谢谢

------解决方案--------------------
select col1,stuff((select ','+b.col2 from tb b where a.col1=b.col1 for xml path('')),1,1,'') from tb a group by col1
------解决方案--------------------
----------------------------
-- 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
----------- ----------------------------------------------------------------------------------------------------------------