sql 多行列转换( case & union all)

以某公司的销售量为例

创建初始数据:

select * into Mytable from(
select 
'上海' as 地区,20 as [2010],30 as[2011],40 as [2012],50 as[2013]
union all
select 
'天津' as 地区,90 as [2010],10 as[2011],31 as [2012],50 as[2013]
union all
select 
'北京' as 地区,60 as [2010],60 as[2011],42 as [2012],50 as[2013]) tb
地区   2010        2011        2012        2013
---- ----------- ----------- ----------- -----------
上海   20          30          40          50
天津   90          10          31          50
北京   60          60          42          50

select 2010 as 年份
,avg(case 地区 when '上海' then [2010] end)  as 上海
,avg(case 地区 when '天津' then [2010] end)  as 天津
,min(case 地区 when '北京' then [2010] end)  as 北京
from Mytable
union all
select 2011 as 年份
,max(case 地区 when '上海' then [2011] end)  as 上海
,max(case 地区 when '天津' then [2011] end)  as 天津
,max(case 地区 when '北京' then [2011] end)  as 北京
from Mytable
union all
select 2012 as 年份
,max(case 地区 when '上海' then [2012] end)  as 上海
,max(case 地区 when '天津' then [2012] end)  as 天津
,max(case 地区 when '北京' then [2012] end)  as 北京
from Mytable
union all
select 2013 as 年份
,max(case 地区 when '上海' then [2013] end)  as 上海
,max(case 地区 when '天津' then [2013] end)  as 天津
,max(case 地区 when '北京' then [2013] end)  as 北京
from Mytable
年份          上海          天津          北京
----------- ----------- ----------- -----------
2010        20          90          60
2011        30          10          60
2012        40          31          42
2013        50          50          50

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值