select 分类,国家,
sum (case when 年代='1996' then 数量 else 0 end) as '1996',
sum (case when 年代='1997' then 数量 else 0 end) as '1997',
sum (case when 年代='1998' then 数量 else 0 end) as '1998',
sum (case when 年代='1999' then 数量 else 0 end) as '1999'
from 表 group by 分类,国家
sum (case when 年代='1996' then 数量 else 0 end) as '1996',
sum (case when 年代='1997' then 数量 else 0 end) as '1997',
sum (case when 年代='1998' then 数量 else 0 end) as '1998',
sum (case when 年代='1999' then 数量 else 0 end) as '1999'
from 表 group by 分类,国家
sum (case 年代 when '1996' then 数量 else 0 end) '1996',
sum (case 年代 when '1997' then 数量 else 0 end) '1997',
sum (case 年代 when '1998' then 数量 else 0 end) '1998',
sum (case 年代 when '1999' then 数量 else 0 end) '1999'
from 表 group by 分类,国家
set @sql=''
select @sql = @sql+ ',sum(case when 年代='''+年代+ '''+ then 数量 else 0 end) as '+ 年代 from (select distinct 年代 from table ) aa
exec ('select 分类,国家 '+@sql +' from tbale group by 分类,国家 ')
不用动态SQL 用
CrazyFor(蚂蚁)
set @sql=''
select @sql = @sql+ ',sum(case when 年代='''+年代+ '''+ then 数量 else 0 end) as '+ 年代 from (select distinct 年代 from table ) aa
exec ('select 分类,国家 '+@sql +' from tbale group by 分类,国家 ')
分类 int,
国家 char(10),
年代 char(4),
数量 int)
insert into #t select 1, '中国', '1996', 1
insert into #t select 1, '英国', '1997', 2
insert into #t select 1, '英国', '1998', 2
insert into #t select 1, '英国', '1999', 2declare @sql varchar(8000)
set @sql='select 分类,国家'
select @sql = @sql+ ',sum(case when 年代='+ 年代+ ' then 数量 else 0 end) as ['+年代+']' from (select distinct 年代 from #t ) aa
exec (@sql +' from #t group by 分类,国家 ')分类 国家 1996 1997 1998 1999
----------- ---------- ----------- ----------- ----------- -----------
1 英国 0 2 2 2
1 中国 1 0 0 0
sum (case year when '1996' then count else 0 end) as '1996',
sum (case year when '1997' then count else 0 end) as '1997',
sum (case year when '1998' then count else 0 end) as '1998',
sum (case year when '1999' then count else 0 end) as '1999'
from country group by id,country
declare @s varchar(8000)
set @s=''
declare a cursor for
select year from country
open a
fetch next from a into @y
while @@fetch_status=0
begin
set @s = @s+',sum(case year when '''+@y+''' then count else 0 end) '''+@y+''''
fetch next from a into @y
end
close a
deallocate a
exec('select id,country'+@s+'from country group by id,country')