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

求一简单sql语句。。。。。。。。

a   1
a   2
a   3
结果
a   1   2   3

------解决方案--------------------

declare @tb table (name varchar(10),id int)
insert into @tb
select 'a ',1
union select 'a ',2
union select 'a ',3

select name,
sum(case id when 1 then id end),
sum(case id when 2 then id end),
sum(case id when 3 then id end)
from @tb group by name
------解决方案--------------------
create table tb(name varchar(10),id int)
insert into tb
select 'a ',1
union select 'a ',2
union select 'a ',3


declare @s varchar(200)
set @s= 'select name '
select @s=@s+ ',sum(case id when ' ' '+rtrim(id)+ ' ' ' then id end) 'from tb group by id

select @s=@s+ ' from tb group by name '
exec(@s)

drop table tb