那麼解決方法有兩種:
1:
select s.year, q.quarter,q.results
from dwtmp.tmp_xn_lsb1 as s,
table (values(1, s.q1),
(2, s.q2),
(3, s.q3),
(4, s.q4))
as q(quarter, results);
核心是用table函數建立了一個表,這個表是用value實現的多行表,value實現虛表
2:
select year, '1' as quarter , q1 as results from dwtmp.tmp_xn_lsb1 union all
select year, '2' as quarter , q2 as results from dwtmp.tmp_xn_lsb1 union all
select year, '3' as quarter , q3 as results from dwtmp.tmp_xn_lsb1 union all
select year, '4' as quarter , q4 as results from dwtmp.tmp_xn_lsb1
order by year,quarter
注:在這個例子中,一個year對應多個quarter,所以橫錶轉縱表時只能利用以上兩種方法,可是,當一個year只對應一個quarter時,那麼能夠用一個case when 語句實現橫轉縱
例如:
建立一個表以下: