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 分类,国家

解决方案 »

  1.   

    select 分类,国家,
      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 分类,国家
      

  2.   

    declare @sql varchar(8000)
    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 分类,国家 ')
      

  3.   

    如果年代是固定的
    不用动态SQL 用
    CrazyFor(蚂蚁)
      

  4.   

    对应Oracle的Decode函数的办法,是不是只有这种?还有没有更好的办法?这种矩阵转置的问题碰到太多次。。
      

  5.   

    declare @sql nvarchar(255)
    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 分类,国家 ')
      

  6.   

    转换前的表格中的数量,已经按照 “分类、国家、年度” 做了分组之后求了和了,所以转换的过程中倒是可以不用 sum ,可是没有什么用来进行转置的函数吗?
      

  7.   

    create table #t(
    分类 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
      

  8.   

    select id,country,
      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
      

  9.   

    declare @y char(4)
    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')