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来完成。
浮躁的人容易问:我到底该学什么;----别问,学就对了; 浮躁的人容易问:JS有钱途吗;----建议你去抢银行; 浮躁的人容易说:我要中文版!我英文不行!----不行?学呀! 浮躁的人分两种:只观望而不学的人;只学而不坚持的人; 浮躁的人永远不是一个高手。