Kettle实现行转列1(场景)

来源:互联网 发布:耽美网络剧 编辑:程序博客网 时间:2024/06/17 08:34

1.固定列数

  1. create table t1
  2. (
  3.     studentno int,
  4.     subject varchar2(10),
  5.     grade int 
  6. );

  7. insert into t1 values(1,'语文',80);
  8. insert into t1 values(1,'数学',82);
  9. insert into t1 values(1,'英语',84);
  10. insert into t1 values(2,'语文',70);
  11. insert into t1 values(2,'数学',74);
  12. insert into t1 values(2,'英语',76);
  13. insert into t1 values(3,'语文',90);
  14. insert into t1 values(3,'数学',93);
  15. insert into t1 values(3,'英语',94);
  16. commit;

  17. SQL> select * from t1;


     STUDENTNO SUBJECT         GRADE
    ---------- ---------- ----------
             1 语文               80
             1 数学               82
             1 英语               84
             2 语文               70
             2 数学               74
             2 英语               76
             3 语文               90
             3 数学               93
             3 英语               94


    已选择9行。

  18. select     studentno 学号,
       sum(decode(subject,'语文',grade,null)) 语文,
       sum(decode(subject,'数学',grade,null)) 数学,
       sum(decode(subject,'英语',grade,null)) 英语
       from t1 group by studentno;


    学号       语文        数学       英语
  19. ----- ---------- ---------- ----------
     1         80         82         84
     2         70         74         76
     3         90         93         94


    使用相关子查询的方式:
  20. select studentno,
    (select grade from t1 v2 where v2.studentno=t1.studentno and v2.subject='语文') 语文,
    (select grade from t1 v2 where v2.studentno=t1.studentno and v2.subject='数学') 数学,
    (select grade from t1 v2 where v2.studentno=t1.studentno and v2.subject='英语') 英语
    from t1 group by studentno;
2.不定列数

  1. create table t2
  2. (
  3.     key int,
  4.     value varchar2(10)
  5. );

  6. insert into t2 values(1,'我');
  7. insert into t2 values(1,'是');
  8. insert into t2 values(1,'谁');
  9. insert into t2 values(2,'知');
  10. insert into t2 values(2,'道');
  11. insert into t2 values(3,'不');
  12. commit;
  13. SQL> select * from t2;

  14.        KEY VALUE
  15. ---------- ----------
  16.          1 我
  17.          1 是
  18.          1 谁
  19.          2 知
  20.          2 道
  21.          3 不

  22. 已选择6行。

  23. with v1 as
    (
        select key,value,row_number() over(partition by key order by key) r from t2
    ),
    v2 as 
    (
        select max(sys_connect_by_path(value,' ')) result from v1 start with r=1 connect by r=prior r+1 and key=prior key group by key
    )
    select * from v2;

  24. RESULT
    ------------------
     我 是 谁
     知 道
     不

如果Oracle版本是11GR2,那么可以使用listagg函数,可以方便很多。

  1. with v1 as
  2. (
  3.     select key,value,row_number() over(partition by key order by key) r from t2
  4. ),
  5. v2 as 
  6. (
  7.     select listagg(value,',') within group (order by r) result from v1 group by key
  8. )
  9. select * from v2;
转自:http://blog.itpub.net/29254281/viewspace-775660/



原创粉丝点击