默认情况下,使用wm_concat和group by拼接字段时,拼接的字段顺序是无规则的。
创建测试数据:
create table tb( seq number(10), remark varchar2(100), createtime date ); insert into tb(seq, remark, createtime) select 1, '说明1', to_date('20210101','yyyymmdd') from dual union all select 1, '说明2', to_date('20210111','yyyymmdd') from dual union all select 1, '说明3', to_date('20210201','yyyymmdd') from dual union all select 1, '说明4', to_date('20210208','yyyymmdd') from dual union all select 5, '说明5', to_date('20210301','yyyymmdd') from dual ;
需求:按照创建日期createtime字段排序,拼接remark字段。
首先,按照wm_concat和group by查询,wm_concat拼接后的结果没有排序。
select seq, wm_concat('[' || to_char(createtime, 'yyyy-mm-dd') || ']' || remark) remark from tb group by seq;
有2种解决方法。
方法1:
使用wm_concat over(partition by 分组字段 order by 排序字段)后,外面再套max和group by 查询
select seq, max(remark) remark from (select seq, wm_concat('[' || to_char(createtime, 'yyyy-mm-dd') || ']' || remark) over(partition by seq order by createtime) remark from tb ) group by seq;
里面一层
select seq, wm_concat('[' || to_char(createtime, 'yyyy-mm-dd') || ']' || remark) over(partition by seq order by createtime) remark from tb
查询结果如下:
方法2:
如果是Oracle 11g以上版本,使用Oracle 11g新增的函数listagg,可以实现按条件列转行,它有2个参数,第1个参数为需要拼接的字段,第2个参数为分隔符(可选)
select seq, listagg('[' || to_char(createtime, 'yyyy-mm-dd') || ']' || remark, ',') within group(order by createtime) remark from tb group by seq;