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來完成。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM