22,209
社区成员
发帖
与我相关
我的任务
分享
declare @a varchar(1000)
select @sql=isnull(@sql+',','')+' max(case when 日期='''+日期+''' then 金额 else 0 end)['+日期+']' from 表 group by 日期
exec('select 名称,'+@sql+' from 表 group by 名称')
declare @sql varchar(8000)
set @sql=''
select @sql=@sql+',['+rtrim(日期)+']=sum(case 日期 when '''+日期+''' then 金额 else 0 end)' from (select distinct 日期 from 表) t
set @sql='select 名称'+@sql+' from 表 group by 名称'
exec(@sql)
if object_id('tb')is not null drop table tb
go
create table tb(金额 money, 日期 varchar(10), 名称 varchar(10))
insert tb select 100 , '200802', 'abc'
insert tb select 85 , '200802' , 'def'
insert tb select 150, '200812' , 'abc'
insert tb select 0 , '200812' ,'def'
select 名称,sum(case when 日期='200802' then 金额 else 0 end)[200802],
sum(case when 日期='200812' then 金额 else 0 end)[200812] from tb group by 名称
/*名称 200802 200812
---------- --------------------- ---------------------
abc 100.0000 150.0000
def 85.0000 .0000*/