日期:2014-05-18  浏览次数:20485 次

如何合并字段显示
有这么一个问题:
  字段名1       字段名2           字段名3
  校长               22                     23
  老师               10                     12
  学生               10                     12

现在要求能合并同类别的,也就是把字段名2和字段名3都相同的记录合并。
合并后的结果为
  字段名1       字段名2           字段名3
  校长               22                     23
  老师、学生             10                     12
想了半天,没有什么好的办法。希望各位高手解答。谢谢



------解决方案--------------------
参考:

--生成测试数据
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)
as
begin
declare @ret varchar(8000)
set @ret = ' '
select @ret = @ret+ ', '+人员 from 表 where 部门 = @department
set @ret = stuff(@ret,1,1, ' ')
return @ret
end
go


--执行
select 部门,人员=dbo.f_str(部门) from 表 group by 部门 order by 部门
go

--输出结果
/*
部门 人员
---- --------------
1 张三,李四,王五
2 赵六,邓七,刘八
*/


--删除测试数据
drop function f_str
drop table 表
go
------解决方案--------------------
create table test (字段名1 varchar(10),字段名2 int,字段名3 int)
insert test
select '校长 ', '22 ', '23 ' union all
select '老师 ', '10 ', '12 ' union all
select '学生 ', '10 ', '12 '
go

create function fn_test(@字段名2 int, @字段名3 int)
returns varchar(8000)
as
begin
declare @return varchar(8000)
select @return = coalesce(@return+ '、 ', ' ') + 字段名1 from test where 字段名2 = @字段名2 and 字段名3 = @字段名3
return (@return)
end
go

select 字段名1 = dbo.fn_test(字段名2, 字段名3), 字段名2, 字段名3 from test group by 字段名2, 字段名3
go

--删除测试
/*
drop table test
drop function fn_test
*/
------解决方案--------------------
1、使用函数,上边的都说了!

2、使用SQL语句,比如:
declare @sql varchar(100)
create table tab1(id varchar(2),name varchar(10))
insert tab1
select '01 ', '张三 '
union
select '02 ', '李四 '
set @sql= ' '
select @sql=@sql+ '、 '+name from tab1
select stuff(@sql,1,1, ' ')
drop table tab1


(2 行受影响)

---------------------------------------------------------------
张三、李四

(1 行受影响)

3、如果里面有null的话,可以使用函数coalesce,例如:
declare @sql varchar(100)
create table tab1(id varchar(2),name varchar(10))
insert tab1
select '01 ', '张三 '
union
select '02 ', '李四 '