您的位置:首页 > 数据库

SQL 将相同记录的所有数据合并为一个字段

2012-10-11 16:43 387 查看
相同姓名的n行记录合并在一个字段,按不重复姓名输出

Sql Code

declare @t table (t varchar(10) ,n varchar(8))
insert into @t
select '2012/7/20', '张三' union all
select '2012/7/21' ,'张三' union all
select '2012/7/20' ,'李四' union all
select '2012/7/20', '王二' union all
select '2012/7/24' ,'麻子' union all
select '2012/7/20', '赵四' union all
select '2012/7/26', '王二' union all
select '2012/7/27', '麻子'

select * from @t

select n, [ts]=stuff((select '|'+[t] from @t t where n=tb.n for xml path('')), 1, 1, '')
from @t tb
group by n

/*

(8 行受影响)
t          n
---------- --------
2012/7/20  张三
2012/7/21  张三
2012/7/20  李四
2012/7/20  王二
2012/7/24  麻子
2012/7/20  赵四
2012/7/26  王二
2012/7/27  麻子

(8 行受影响)

n        ts
-------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
李四       2012/7/20
麻子       2012/7/24|2012/7/27
王二       2012/7/20|2012/7/26
张三       2012/7/20|2012/7/21
赵四       2012/7/20

(5 行受影响)

*/


另附:SQL Server FOR XML PATH 语句的应用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐