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

SQL SERVER2000行转为列的难题!
有一张数据表A
 DeviceID(numeric) ItemID(numeric) OrganizationID(numeric)
  21 23 282
  21 24 282
  21 25 282
  22 23 282
  22 24 282 
喜欢能得到这样的结果:
  DeviceID ItemID OrganizationID
  21 23,24,25 282
  22 23,24 282

如何来完成?先谢谢各位

------解决方案--------------------
--带符号合并行列转换

--有表t,其数据如下:
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

if object_id('pubs..f_hb') is not null
drop function f_hb
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

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

(所影响的行数为 3 行)