如何从sql oracle查询中获取特殊的grouped by,嵌套json?

hmmo2u0o  于 2023-04-29  发布在  Oracle
关注(0)|答案(2)|浏览(225)

代码如下所示:

SELECT 
JSON_OBJECT(
ROOM_LIGHT VALUE
JSON_OBJECT
(
'START' VALUE START,
'ENDE' VALUE ENDE,
'RUN' VALUE RUNNING
)
) 
FROM runtime

WHERE 1 = 1
GROUP BY ROOM_LIGHT;

我想要回这个JSON:

{
"ROOM_LIGHT": "01": [
{
"START" :"",
"ENDE"  :"",
"RUNNING": ""
},
{
"START" :"",
"ENDE"  :"", 
"RUNNING": ""
}
],
"ROOM_LIGHT": "02": [
{
"START" :"",
"ENDE"  :"",
"RUNNING": ""
},
{
"START" :"",
"ENDE"  :"", 
"RUNNING": ""
}
]
}

我的问题是分组不起作用。我得到了这样的JSON:

{ "ROOM_LIGHT 01": {"START": "", "ENDE":"", "RUNNING":""}},
{ "ROOM_LIGHT 01": {"START": "", "ENDE":"", "RUNNING":""}},
{ "ROOM_LIGHT 01": {"START": "", "ENDE":"", "RUNNING":""}}
laik7k3q

laik7k3q1#

您的预期输出是无效的JSON,因为您在同一对象中有多个键,并且具有相同的ROOM_LIGHT键。
使用JSON_ARRAYAGG

SELECT JSON_OBJECT(
         KEY 'ROOM_LIGHT ' || ROOM_LIGHT VALUE JSON_ARRAYAGG(
           JSON_OBJECT(
             KEY 'START' VALUE "START",
             KEY 'ENDE'  VALUE ENDE,
             KEY 'RUN'   VALUE RUNNING
           )
         )
       ) As json
FROM   runtime
GROUP BY ROOM_LIGHT;

其中,对于样本数据:

CREATE TABLE runtime (
  room_light VARCHAR2(20),
  "START"    VARCHAR2(20),
  ende       VARCHAR2(20),
  running    VARCHAR2(20)
);

INSERT INTO runtime (room_light, "START", ende, running)
SELECT '01', 'abc', 'def', 'Y' FROM DUAL UNION ALL
SELECT '01', 'ghi', 'jkl', 'Y' FROM DUAL UNION ALL
SELECT '01', 'mno', 'pqr', 'N' FROM DUAL UNION ALL
SELECT '02', 'stu', 'vwx', 'Y' FROM DUAL;
  • 注意:START是一个保留字,除非使用带引号的标识符,否则不能用作标识符。*

输出:
| JSON|
| --------------|
| Copyright © 2018 - 2019深圳市创科光电科技有限公司All Rights Reserved.粤ICP备16018888号-1|
| © 2018 - 2019 www.cn-rn.com版权所有并保留所有权利|
fiddle

更新

如果字符串的大小有问题,那么使用RETURNING CLOB返回CLOB,而不是VARCHAR2

SELECT JSON_OBJECT(
         KEY 'ROOM_LIGHT ' || ROOM_LIGHT VALUE JSON_ARRAYAGG(
           JSON_OBJECT(
             KEY 'START' VALUE "START",
             KEY 'ENDE'  VALUE ENDE,
             KEY 'RUN'   VALUE RUNNING
             RETURNING CLOB
           )
           RETURNING CLOB
         )
         RETURNING CLOB
       ) As json
FROM   runtime
GROUP BY ROOM_LIGHT;

fiddle

yebdmbv4

yebdmbv42#

你必须使用JSON_ARRAYAGG将元素分组到一个数组中:

SELECT ROOM_LIGHT, 
        JSON_OBJECT(
          'ROOM_LIGHT : ' || ROOM_LIGHT value
          JSON_ARRAYAGG(
           JSON_OBJECT (
             'START' VALUE STARTE,
             'ENDE' VALUE ENDE,
             'RUNE' VALUE RUNNING
           )
          )
         ) as json
FROM runtime
GROUP BY ROOM_LIGHT;

结果:

ROOM_LIGHT  JSON
01          {"ROOM_LIGHT : 01":[{"START":10,"ENDE":4,"RUNE":5},{"START":10,"ENDE":14,"RUNE":5}]}
02          {"ROOM_LIGHT : 02":[{"START":10,"ENDE":4,"RUNE":5}]}

Demo here

相关问题