随笔 - 24  文章 - 0  评论 - 2  阅读 - 69089

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

posted on   慢慢走~  阅读(9459)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示