关于oracle和db2中的纵表转横表的例子

在数据库开发的过程中,经常会遇到把纵表的数据转换为横表展示出来。今天我就把经常遇到的实现的方法总结出来,还请大家指点错误啊。或者有更好的方法,也可以让我学习学习。
     ---以下脚本是在db2中实现的
     第一个:纵表转横表的"SQL"示例
     纵表结构: TEST_vip
     acct_month       卡级别             数量
     201201            钻卡              1
     201201            金卡              2
     201201            银卡              3

     转换后显示如下
     acct_month  钻卡数量  金卡数量  银卡数量
     201201       1         2         3
    
     实现思路为先将表中的数据构造成需要展示的列数,再在最外层将此值全部累加即可。

     实现的sql为:
      select acct_month,
             sum(zk_count),
             sum(jk_count),
             sum(yk_count)
      from (select acct_month,
                   case when card_level = '钻卡' then card_count end as zk_count,
                    case when card_level = '金卡' then card_count end as jk_count,
                    case when card_level = '银卡' then card_count end as yk_count
            from TEST_vip
         ) group by acct_month;
    

       第二个:
       表结构如下:
       表1                          表2
       字段1   字段2            字段3  字段4
       A        1               A       1,2,3
       A        2               B       5,6
       A        3               C       7,8,9
       B        5
       B        6
       C        7
       C        8
       C        9

       转换要求:
      使用sql实现,汇总表1字段1,字段2值用逗号隔开写入表2字段4


      实现的sql为:
      create table test_lyq(f1 varchar(3), f2 integer);

      insert into test_lyq
      values
      ('A',1),
      ('A',2),
      ('A',3),
      ('B',5),
      ('B',6),
      ('C',7),
      ('C',8),
      ('C',9);

     WITH TMP(c1,c2,c3) as
    (
       select f1,f2,char(f2)          from test_lyq
        where (f1,f2) in (select f1,min(f2) from test_lyq group by f1)

       union all

       select t1.c1,t1.c2+1,rtrim(t1.c3)||','||rtrim(char(t2.f2)) from tmp t1 , test_lyq t2
       where t1.c1 = t2.f1 and t1.c2+1 = t2.f2
     )
     select c1,c3 from tmp where (c1,c2) in (select f1,max(f2) from test_lyq group by f1);
































































































猜你喜欢

转载自beliveada.iteye.com/blog/1469032
今日推荐