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

發佈了34 篇原創文章 · 獲贊 16 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章