我想在下面的 SQL 查询中使用 offset 并获取下一个子句,但它抛出错误“ORA-00937:不是单组组函数”,请帮助我如何在下面的查询中使用 offset 并获取下一个子句保留响应格式
DECLARE
l_json_object JSON_OBJECT_T;
l_json CLOB;
BEGIN
SELECT
JSON_OBJECT(
KEY 'employees' VALUE
JSON_ARRAYAGG(
JSON_OBJECT(KEY 'empno' VALUE id
,KEY 'ename' VALUE name
,KEY 'job' VALUE email_id)
ORDER BY id
RETURNING CLOB)
RETURNING CLOB)
INTO l_json
FROM employee_tbl
ORDER BY
id DESC OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY;
-- now convert clob to JSON_OBJECT_T
l_json_object := JSON_OBJECT_T.PARSE(l_json);
-- or...this works too
-- l_json_object := JSON_OBJECT_T(l_json);
-- check if value is correct
dbms_output.put_line(l_json_object.to_clob);
END;
/
表格示例:
CREATE TABLE employee_tbl (id, name, email_id) AS
SELECT 1065, 'Abu', '[email protected]' FROM DUAL UNION ALL
SELECT 1066, 'Umar', '[email protected]' FROM DUAL
预期输出:
{"employees":[{"empno":1065,"ename":"Abu","job":"[email protected]"},{"empno":1066,"ename":"Umar","job":"[email protected]"}]}
您正在选择单个值(恰好是 CLOB)到标量变量中,因此行限制(偏移/获取)甚至排序都没有意义。
假设您尝试仅获取 JSON 数组中的最后 5 名员工(按 ID),您可以先过滤表结果,然后再转换为 JSON。
代替:
INTO l_json
FROM employee_tbl
ORDER BY
id DESC OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY;
您可以使用子查询(内联视图)来限制基表中的行:
FROM (
SELECT id, name, email_id
FROM employee_tbl
ORDER BY id DESC
OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY
);