当前位置: 代码迷 >> Sql Server >> 怎么合并相同ID的多条纪录
  详细解决方案

怎么合并相同ID的多条纪录

热度:154   发布时间:2016-04-27 19:29:29.0
如何合并相同ID的多条纪录
数据库 sqlserver,现有数据表结构如下: 
id name 
1 a 
1 b 
1 c 
2 d 
2 e 
3 f 
现在想合并得到如下效果: 
id name 
1 a,b,c 
2 d,e 
3 f 
sql语句应该怎么写?

------解决方案--------------------
参考以下示例:

SQL code
--生成测试数据create table 表(部门 int,人员 varchar(20))insert into 表 select 1,'张三'insert into 表 select 1,'李四'insert into 表 select 1,'王五'insert into 表 select 2,'赵六'insert into 表 select 2,'邓七'insert into 表 select 2,'刘八'go--创建用户定义函数create function f_str(@department int)returns varchar(8000)asbegin    declare @ret varchar(8000)    set @ret = ''    select @ret = @ret+','+人员 from 表 where 部门 = @department    set @ret = stuff(@ret,1,1,'')    return @ret endgo--执行select 部门,人员=dbo.f_str(部门) from 表 group by 部门 order by 部门go--输出结果/*部门  人员----  --------------1     张三,李四,王五2     赵六,邓七,刘八*/--删除测试数据drop function f_strdrop table 表go
  相关解决方案