Oracle JSON_ARRAYAGG 和 Limit/Rownum

Oracle JSON_ARRAYAGG with Limit/Rownum

我正在使用 Oracle 19c 和 JSON_ARRAYAGG 函数(使用 JSON_OBJECT)来 return 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;       

 

您可以先select子查询中的前 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