【问题标题】:Oracle JSON_ARRAYAGG with Limit/Rownum具有限制/Rownum 的 Oracle JSON_ARRAYAGG
【发布时间】:2020-11-16 06:18:17
【问题描述】:

我正在使用 Oracle 19c 和 JSON_ARRAYAGG 函数(使用 JSON_OBJECT)返回 JSON 对象的串联数组字符串。我需要根据 ORDER BY SENT_DATE DESC 将结果限制为前 10 个对象

注意JSON_ARRAYAGG 有自己的ORDER BY,所以我把它放在那里。但是,有限制设施吗?

以下语法正确,但结果不正确。我的 JSON 对象在串联字符串中不是 SENT_DATE DESC 顺序。

SELECT json_arrayagg(json_object('sentDate' value mh.sent_date, 
                                 'sentByEmail' value mh.send_by_email,  
                                 'sentBy' value mh.sent_by, 
                                 'sentByName' value mh.sent_by_name,  
                                 'sentToEmail' value mh.sendee_email)  
                                 ORDER BY mh.sent_date DESC) /*ORDER BY inside json_arrayagg)*/
                                                             /*Normally this works, but not with ROWNUM*/
    from mail_history_t mh 
    where mh.plan_id = 763 and mh.is_current_status = 'Y' and rownum <= 10; /*ROWNUM outside*/

如果我在通常的行查询中检查顶部结果,我发现这是不正确的,

select * from mail_history_t where plan_id = 763 and is_current_status ='Y' order by sent_date desc;       

 

【问题讨论】:

    标签: sql arrays json oracle oracle19c


    【解决方案1】:

    您可以先选择子查询中的前 10 行,使用fetch first 行限制子句,然后在外部查询中聚合:

    select json_arrayagg(
        json_object(
            'sentDate'    value sent_date, 
            'sentByEmail' value send_by_email,  
            'sentBy'      value sent_by, 
            'sentByName'  value sent_by_name,  
            'sentToEmail' value sendee_email
        )  
        order by sent_date desc
    ) js_array
    from (
        select *
        from mail_history_t
        where plan_id = 763 and  is_current_status = 'Y'
        order by sent_date desc
        fetch first 10 rows only
    ) t
    

    【讨论】:

    • 谢谢,JSON_AGGARRAYinternal ORDER BY 在此之后还需要吗?
    • @geneb.: 它做了不同的事情,即在 json 数组中 对元素进行排序(如果您想要确定性的结果,这通常是一件好事 - 否则数据库可以随意排序数组元素)。
    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    相关资源
    最近更新 更多