DB2中橫表縱表互換

一、列轉行:
建立一個以下的表
drop table dwtmp.tmp_xn_lsb;
create table dwtmp.tmp_xn_lsb
(
year      int
,quarter   int
,results    int
)distribute by hash(year)in tbs_dwd;

insert into dwtmp.tmp_xn_lsb
values (2004,1,20)
union all values (2004,2,30)
union all values (2004,3,15)
union all values (2004,4,10)
union all values (2005,1,18)
union all values (2005,2,40)
union all values (2005,3,12)
union all values (2005,4,27)

要獲得以下結果:


那麼方法以下:
select 
      year
      ,max(case when quarter = 1 then results end) as q1
      ,max(case when quarter = 2 then results end) as q2
      ,max(case when quarter = 3 hen results end) as q3
      ,max(case when quarter = 4 then results end) as q4
from dwtmp.tmp_xn_lsb
group by year

      

二、行轉列:
建立以下表:


想要獲得結果:


那麼解決方法有兩種:
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 語句實現橫轉縱






例如:
建立一個表以下:


想獲得結果以下:


此時,一個year只歸屬一個quarter那麼,還可用case when 的方法來轉置:
select         year           ,case when q1  is not null then 1              when q2  is not null then 2              when q3  is not null then 3              when q4  is not null then 4 end as quarter     ,case when q1  is not null then q1             when q2  is not null then q2             when q3  is not null then q3             when q4  is not null then q4 end as results from      dwtmp.tmp_xn_lsb3 order by year   
相關文章
相關標籤/搜索