【问题标题】:How to filter with group by or distinct clause in constricting oracle json_array如何在限制 oracle json_array 中使用 group by 或 distinct 子句进行过滤
【发布时间】:2020-06-04 09:36:24
【问题描述】:

拥有简单的数据库结构

PERSON_ID   FIRST_NAME  LAST_NAME
1             John          Doe
2             John          Doe
3             Peter       Jackson

需要使用 JSON ARRAY 结构构建单行输出,其中包含按 first_name,last_name 条件过滤的唯一数据。

预期结果:

[{
    "firstname": "John",
    "lastname": "Doe"
},
{
    "firstname": "Peter",
    "lastname": "Jackson"
}] 

在数组级别使用 group by 会产生两行

SELECT  json_array(   
                    json_object(  key 'firstname' VALUE t.first_name, 
                                  key 'lastname'  VALUE t.last_name)

                 ) RESPONSEJSON

FROM TESTDATA t
GROUP BY t.first_name, t.last_name



    RESPONSEJSON
1   [{"firstname":"Peter","lastname":"Jackson"}]
2   [{"firstname":"John","lastname":"Doe"}]

【问题讨论】:

    标签: sql arrays json oracle object


    【解决方案1】:

    使用子查询来创建不同的对象。然后将它们聚合到数组中:

    create table t (
      person_id int, first_name varchar2(10), last_name varchar2(10)
    );
    
    insert into t values (1, 'John', 'Doe' );
    insert into t values (2, 'John', 'Doe' );
    insert into t values (3, 'Peter', 'Jackson' );
    commit;
    
    with jobjs as (
      select  distinct json_object(  
                key 'firstname' VALUE t.first_name, 
                key 'lastname'  VALUE t.last_name
              ) responsejson
      from    t
    )
    SELECT  json_arrayagg ( responsejson )
    FROM    jobjs;
    
    [
      {"firstname":"John","lastname":"Doe"},
      {"firstname":"Peter","lastname":"Jackson"}
    ]
    

    在 12.2 中存在一个错误,当使用上述 distinct 时会给出错误的结果。你可以改用group by 来解决这个问题:

    with jobjs as (
      select  json_object(  
                key 'firstname' VALUE t.first_name, 
                key 'lastname'  VALUE t.last_name
              ) responsejson
      from    t
      group   by t.first_name, t.last_name
    )
    SELECT  json_arrayagg ( responsejson )
    FROM    jobjs;
    
    [
      {"firstname":"Peter","lastname":"Jackson"},
      {"firstname":"John","lastname":"Doe"}
    ]   
    

    【讨论】:

    • 是单个查询?
    • 对不起,我的错,以前从未使用过 WITH SELECT。但是对于您的示例,结果是: [{"firstname":"John","lastname":"Doe"},{"firstname":"John","lastname":"Doe"},{"firstname" :"Peter","lastname":"Jackson"}]
    • 您使用的是哪个版本的 Oracle 数据库?
    • 有一个 12.2 的错误(已在 19c 中修复)与 distinct;你可以使用 group by 代替
    • 12.2,分组一切正常。谢谢克里斯
    猜你喜欢
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多