select BIG,sum(case when SMALL='a' then COUNT else 0 end ) as aa,
sum(case when SMALL='b' then COUNT else 0 end ) as bb,
sum(case when SMALL='c' then COUNT else 0 end ) as cc
from table1
group by BIG
sum(case when SMALL='b' then COUNT else 0 end ) as bb,
sum(case when SMALL='c' then COUNT else 0 end ) as cc
from table1
group by BIG
create table ttttt(编号 varchar(20),序号 int,价格 int,数量 int)
insert ttttt values('1234',1,40,20)
insert ttttt values('1234',3,43,25)
insert ttttt values('5678',1,40,30)
insert ttttt values('5678',3,43,20)
insert ttttt values('5678',1,40,32)
insert ttttt values('5678',2,40,32)--查看数据
select * from ttttt--查看结果
declare @sql varchar(2000)
set @sql='select 编号'
select @sql=@sql+',[序号'+convert(varchar(20),序号)+']=isnull(sum(case when 序号='+convert(varchar(20),序号)+' then 数量 end),0)'
from ttttt
group by 序号select @sql=@sql+',[价格合计]=sum(价格*数量) from ttttt group by 编号'
print @sqlexec(@sql)drop table ttttt
--这个是针对上面的语句写的动态的语句,这样维护要方便点,但都是采用相同的算法
insert into test_temp
select 'A', 'a', 1 union
select 'A', 'b', 2 union
select 'B', 'a', 2 union
select 'B', 'c', 3 union
select 'C', 'a', 4select distinct small into #t from test_temp
declare @sql varchar(8000)
set @sql = ''select @sql = @sql + ',sum(isnull((case when small=''' + small + ''' then count else 0 end),0)) as ' + small from #t
print('select big' + @sql + ' from test_temp')
exec('select big' + @sql + ' from test_temp group by big')drop table #t
drop table test_temp