高分求一非常复杂的SQL语句~~很有难度~~

sprite14 2003-03-19 11:59:24
现在有一个表,结构如下
名称 月份 金额
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

请问有办法吗?
谢谢
...全文
268 15 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
yoki 2003-03-19
  • 打赏
  • 举报
回复
CONVERT与CAST功能一样
sprite14 2003-03-19
  • 打赏
  • 举报
回复
不对
应该是用哪个CONVERT转换吧
pengdali 2003-03-19
  • 打赏
  • 举报
回复
难道我的写错了吗?
还是你没试?
funboy88 2003-03-19
  • 打赏
  • 举报
回复
哈,现在才看到,搞错啦,
用我上铺兄弟的吧,转换成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
funboy88 2003-03-19
  • 打赏
  • 举报
回复
不用理会是不是字符型了
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 名称

yoki 2003-03-19
  • 打赏
  • 举报
回复
:-( 不好意思
如果你是字符型的话
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 名称
sprite14 2003-03-19
  • 打赏
  • 举报
回复
sum不能运算字符类型
yoki 2003-03-19
  • 打赏
  • 举报
回复
如果你是字符型的话
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 名称
yoki 2003-03-19
  • 打赏
  • 举报
回复
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 名称
ben988211 2003-03-19
  • 打赏
  • 举报
回复
这里一直都很好
sprite14 2003-03-19
  • 打赏
  • 举报
回复
我的月份是不是数值类型,如何转换?
zqllyh 2003-03-19
  • 打赏
  • 举报
回复
哈,难怪SQL的人气这么旺。
zqllyh 2003-03-19
  • 打赏
  • 举报
回复
select 名称 sum(case 月份 when 1 then 金额 else 0 end) as 1月份金额...
from table group by 名称
hillhx 2003-03-19
  • 打赏
  • 举报
回复
select sum(case 月份 when 1 then 金额 end),sum(case 月份 when 2 then 金额 end)
from tab1
group by 名称
pengdali 2003-03-19
  • 打赏
  • 举报
回复
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)

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧