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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值