declare @sql varchar(8000)
set @sql = 'select 名称,'
select @sql = @sql + 'sum(case 月份 when '+cast(月份 as varchar)+' then 金额 else 0 end) '+cast(月份 as varchar)+'月份金额 ,'
  from (select distinct 月份 from 有一个表) as a
set @sql = left(@sql,len(@sql)-1) + ' from 有一个表 group by 名称'
exec(@sql)

解决方案 »

  1.   

    select sum(case 月份 when 1 then 金额 end),sum(case 月份 when 2 then 金额 end)
    from tab1
    group by 名称
      

  2.   

    select 名称   sum(case 月份 when 1 then  金额 else 0 end) as 1月份金额...
    from table group by 名称
      

  3.   

    select 名称,sum(case 月份 when 1 then 金额 else null end ) a1,
                sum(case 月份 when 2 then 金额 else null end ) a2,
                sum(case 月份 when 3 then 金额 else null end ) a3
    from @  
    group by 名称
      

  4.   

    如果你是字符型的话
    select 名称,sum(case 月份 when '1' then 金额 else null end ) a1,
                sum(case 月份 when '2' then 金额 else null end ) a2,
                sum(case 月份 when '3' then 金额 else null end ) a3
    from @  
    group by 名称
      

  5.   

    :-( 不好意思
    如果你是字符型的话
    select 名称,sum(case cast(月份 as int) when 1 then 金额 else null end ) a1,
                sum(case cast(月份 as int) when 2 then 金额 else null end ) a2,
                sum(case cast(月份 as int) when 3 then 金额 else null end ) a3
    from @  
    group by 名称
      

  6.   

    不用理会是不是字符型了
    select 名称,sum(case cast(月份 as varchar(2)) when '1' then 金额 else null end ) 1月份金额,
                sum(case cast(月份 as varchar(2)) when '2' then 金额 else null end ) 2月份金额,
                sum(case cast(月份 as varchar(2)) when '3' then 金额 else null end ) 3月份金额
    from 表名
    group by 名称
      

  7.   

    哈,现在才看到,搞错啦,
    用我上铺兄弟的吧,转换成INT型select 名称,sum(case cast(月份 as int) when 1 then 金额 else 0 end ) a1,
                sum(case cast(月份 as int) when 2 then 金额 else 0 end ) a2,
                sum(case cast(月份 as int) when 3 then 金额 else 0 end ) a3
    from @  
    group by 名称最好把NULL转换成0
      

  8.   

    不对
    应该是用哪个CONVERT转换吧