zoukankan      html  css  js  c++  java
  • 【Oracle】listagg函数使用及其在11g版本上的潜藏坑

    listagg能把非分组列的信息归并一起,能在分组查询语句中和count,avg,sum及分组列并列查询,也算一绝。其基本用法如下:

    建表:

    create table emp6(
        id number(8),
        name nvarchar2(20),
        vocation nvarchar2(20),
        primary key(id)
    )

    充值:

    insert into emp6(id,name,vocation) values(1,'andy','worker');
    insert into emp6(id,name,vocation) values(2,'bill','worker');
    insert into emp6(id,name,vocation) values(3,'cindy','worker');
    insert into emp6(id,name,vocation) values(4,'douglas','doctor');
    insert into emp6(id,name,vocation) values(5,'eliot','doctor');
    insert into emp6(id,name,vocation) values(6,'felix','nurse');

    现在想按职业分组,有想知道哪个职业有哪些人,listagg函数正好派上用场:

    select count(*) as cnt,vocation,listagg(name,',') within group(order by 1) as names from emp6 group by vocation 

    执行结果:

    SQL> select count(*) as cnt,vocation,listagg(name,',') within group(order by 1) as names from emp6 group by vocation ;
    
           CNT VOCATION             NAMES
    ---------- -------------------- ----------------------------------------
             2 doctor               douglas,eliot
             3 worker               andy,bill,cindy
             1 nurse                felix

    这是在oracle19c上的效果,没啥毛病。

    但是,在11g上就是这个效果:

    SQL> select count(*) as cnt,vocation,listagg(name,',') within group(order by 1) as names from emp6 group by vocation;
    
           CNT VOCATION
    ---------- ----------------------------------------
    NAMES
    ----------------------------------------
             2 doctor
     d o u g l a s, e l i o t
    
             1 nurse
     f e l i x
    
             3 worker
     a n d y, b i l l, c i n d y

    而且,出来的结果里的空白字符,用java的Character.isWhiteSpace是区别不出来的,用正则表达式\\s+也没有用...

    要解决也很简单,用to_char函数将name字段包一下就好了,如下:

    select count(*) as cnt,vocation,listagg(to_char(name),',') within group(order by 1) as names from emp6 group by vocation

    执行效果:

    SQL> select count(*) as cnt,vocation,listagg(to_char(name),',') within group(order by 1) as names from emp6 group by vocation;
    
           CNT VOCATION             NAMES
    ---------- -------------------- ----------------------------------------
    2             doctor               douglas,eliot
    1             nurse                felix
    3             worker               andy,bill,cindy

    END

  • 相关阅读:
    $.ajax()、$.post()、$.get()
    Json数据格式
    iOS UIButton 调节文字和图片的位置
    block 中使用 weakSelf
    iOS 移除导航栏黑线
    Swift 设置导航栏透明
    Xcode 8 证书管理 Signing for "xxxx" requires a development team.
    iOS 中文登录 中文参数 转码
    ios apple pay 证书配置
    Missing iOS Distribution signing identity for ... Xcode can request one for you.
  • 原文地址:https://www.cnblogs.com/heyang78/p/15673752.html
Copyright © 2011-2022 走看看