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)
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)
from tab1
group by 名称
from table group by 名称
sum(case 月份 when 2 then 金额 else null end ) a2,
sum(case 月份 when 3 then 金额 else null end ) a3
from @
group by 名称
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 名称
如果你是字符型的话
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 名称
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 名称
用我上铺兄弟的吧,转换成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
应该是用哪个CONVERT转换吧