sql2000行转列

来源:互联网 发布:找最大值 java 方法 编辑:程序博客网 时间:2024/05/22 15:47

 有表tb,其数据如下:
  a b
  1 1
  1 2
  1 3
  2 1
  2 2
  3 1
如何转换成如下结果:
  a b
  1 1,2,3
  2 1,2
  3 1
*/

create table tb
(
   a int,
   b int
)
insert into tb(a,b) values(1,1)
insert into tb(a,b) values(1,2)
insert into tb(a,b) values(1,3)
insert into tb(a,b) values(2,1)
insert into tb(a,b) values(2,2)
insert into tb(a,b) values(3,1)
go

 

关键函数:

--创建一个合并的函数
create function f_hb(@a int)
returns varchar(8000)
as
begin
  declare @str varchar(8000)
  set @str = ''
  select @str = @str + ',' + cast(b as varchar) from tb where a = @a
  set @str = right(@str , len(@str) - 1)
  return(@str)
End
go

--调用自定义函数得到结果:
select distinct a ,dbo.f_hb(a) as b from tb

drop table tb
drop function f_hb

/*
结果
a           b    
----------- ------
1           1,2,3
2           1,2
3           1