22,209
社区成员
发帖
与我相关
我的任务
分享
create table 表(id int,姓名 varchar(20),钱 int)
insert into 表 select 1,'张三',10
insert into 表 select 2,'李四',20
insert into 表 select 3,'王麻子',30
go
declare @str varchar(8000)
set @str='select id'
select @str=@str+',['+rtrim(姓名)+']=sum(case 姓名 when '''+姓名+''' then 钱 else 0 end)' from (select distinct 姓名 from 表) t
set @str=@str+' from 表 group by id'
exec(@str)
/*
id 李四 王麻子 张三
----------- ----------- ----------- -----------
1 0 0 10
2 20 0 0
3 0 30 0
*/
go
drop table 表
go
declare @str varchar(8000)
set @str='select id'
select @str=@str+',['+rtrim(姓名)+']=sum(case 姓名 when '''+姓名+''' then 钱 else 0 end)' from (select distinct 姓名 from 表) t
set @str=@str+' from 表 group by id'
exec(@sql)