zoukankan      html  css  js  c++  java
  • Oracle中wm_concat与listagg函数的用法及区别

    1.初始的sql:

    select t.* from wp_shipinto t where substr(to_char(t.pshipdate),0,6) = '201907';

     查询结果:

     

    2.wm_concat函数:使用group by来对itemcode,年月进行分组,分组后行转列显示:

    select s.itemcode,substr(to_char(s.pshipdate),0,6) as yearmonth,wm_concat(s.pshipqty)  from (select t.* from  wp_shipinto t order by t.pshipdate asc) s
    where substr(to_char(s.pshipdate),0,6) = '201907'
    group by substr(to_char(s.pshipdate),0,6),s.itemcode;

    查询结果(左图):

      

    我们以ITEMCODE为1542的数据为例,可以看到虽然在sql中已经对pshipdate进行升序排序,但是在分组、行转列之后,yearmonthqty中的数据并不是根据日期升序来排列的。

    因为在group by之后会打乱原来的顺序。

    3. listagg函数:使用group by对itemcode,年月进行分组,行转列:

    select t.itemcode,substr(to_char(t.pshipdate),0,6) as yearmonth,listagg(t.pshipqty,',') within group(order by t.pshipdate asc) as yearmonthqty from wp_shipinto t 
    where substr(to_char(t.pshipdate),0,6) = '201907'
    group by substr(to_char(t.pshipdate),0,6),t.itemcode;

    查询结果:

     yearmonthqty是根据pshipdate升序排列的。

     总结:wm_cancat函数行转列后,不会按照原有查询结果排序。listagg函数行转列后,会按照原有查询结果顺序排列。

                如果考虑到需要行转列,并且保持分组后顺序不变可以使用listagg来完成。

  • 相关阅读:
    EM and GMM(Code)
    EM and GMM(Theory)
    安装Sphere v2.7 遇到的问题
    pyqt的 .ui 转换为 .py 后的操作注意事项
    SVM入门(一)
    关于范数的理解
    快速排序的C语言实现
    QT编程环境搭建
    flex布局左边固定,右边自适应,右边内容超出会影响布局
    未知宽高的div怎么垂直水平居中
  • 原文地址:https://www.cnblogs.com/qianlang/p/11268997.html
Copyright © 2011-2022 走看看