现在有一个表,结构如下
名称 月份 金额
A 1 100
A 2 200
B 2 210
C 2 220
C 3 320
想想用SQL得出这样的结果
名称 1月份金额 2月份金额 3月份金额
A 100 200 NULL
B NULL 210 NULL
C NULL 220 320
请问有办法吗?
谢谢
...全文
26815打赏收藏
高分求一非常复杂的SQL语句~~很有难度~~
现在有一个表,结构如下 名称 月份 金额 A 1 100 A 2 200 B 2 210 C 2 220 C 3 320 想想用SQL得出这样的结果 名称 1月份金额 2月份金额 3月份金额 A 100 200 NULL B NULL 210 NULL C NULL 220 320 请问有办法吗? 谢谢
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 名称
不用理会是不是字符型了
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 名称
:-( 不好意思
如果你是字符型的话
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 月份 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 月份 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 名称
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)