將行转成列的统计SQL

create table #t(shopid varchar(10), procid varchar(10), qty int)
insert into #t
select 'AAAAA',    '00001',   10
union all select 'AAAAA',    '00002',   20
union all select 'AAAAA',    '00003',   10
union all select 'AAAAA',    '00004',   30
union all select 'BBBBB',    '00001',   10
union all select 'BBBBB',    '00002',   20
union all select 'BBBBB',    '00003',   10
union all select 'BBBBB',    '00004',   30
select * from #t
go

declare @sql varchar(8000)
set @sql='select shopid'
select @sql=@sql+','+quotename(procid)+'=sum(case procid when '''+procid+''' then qty else 0 end)'
from (select distinct(procid) from #t) a
exec(@sql+' from #t group by shopid')

drop table #t

你可能感兴趣的:(將行转成列的统计SQL)