带有基于ORDER BY的限制/舍入的Oracle JSON_ARRAYAGG

vwhgwdsa  于 2022-11-03  发布在  Oracle
关注(0)|答案(1)|浏览(169)

我正在使用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;
pkwftd7m

pkwftd7m1#

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

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

相关问题