DB2中横表纵表互换

1、列转行:
创建一个如下的表
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

      

2、行转列:
创建如下表:


想要得到结果:


那么解决方法有两种:
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   
原文地址:https://www.cnblogs.com/xuena/p/3912036.html