gpt4 book ai didi

sql - 如何从表中的 oracle sql 中选择带有 group by 子句的嵌套 json 对象?

转载 作者:行者123 更新时间:2023-12-05 02:47:14 27 4
gpt4 key购买 nike

假设我有以下声明:

WITH t AS
(
SELECT 'A' AS level_0, 'A1' AS level_1_1, 'object_1' AS level_1_2, 'A11' AS level_2_1, 'B11' AS level_2_2 FROM dual
UNION ALL
SELECT 'A' AS level_0, 'A1' AS level_1_1, 'object_1' AS level_1_2, 'A12' AS level_2_1, 'B12' AS level_2_2 FROM dual
UNION ALL
SELECT 'A' AS level_0, 'A1' AS level_1_1, 'object_1' AS level_1_2, 'A13' AS level_2_1, 'B13' AS level_2_2 FROM dual
UNION ALL
SELECT 'A' AS level_0, 'A1' AS level_1_1, 'object_1' AS level_1_2, 'A14' AS level_2_1, 'B14' AS level_2_2 FROM dual
UNION ALL
SELECT 'B' AS level_0, 'A1' AS level_1_1, 'object_2' AS level_1_2, 'A11' AS level_2_1, 'B15' AS level_2_2 FROM dual
UNION ALL
SELECT 'B' AS level_0, 'A1' AS level_1_1, 'object_2' AS level_1_2, 'A12' AS level_2_1, 'B16' AS level_2_2 FROM dual
UNION ALL
SELECT 'B' AS level_0, 'A1' AS level_1_1, 'object_2' AS level_1_2, 'A13' AS level_2_1, 'B17' AS level_2_2 FROM dual
)
SELECT * FROM t

我想要的输出是这样的:


+---------+---------------------------------------------------------------------------------+
| Level 0 | JSON |
+---------+---------------------------------------------------------------------------------+
| A | {"level_1_1":"A1","object_1":{"A11":"B11","A12":"B12","A13":"B13","A14":"B14"}} |
| B | {"level_1_1":"A1","object_2":{"A11":"B15","A12":"B16","A13":"B17"}} |
+---------+---------------------------------------------------------------------------------+

如何使用 select 语句获得此输出?

非常感谢您的帮助!

最佳答案

JSON_OBJECT()JSON_OBJECTAGG() 函数可以与适当的分组一起使用,例如

SELECT level_0,
JSON_OBJECT(
'level_1_1' VALUE level_1_1,
level_1_2 VALUE JSON_OBJECTAGG(level_2_1 VALUE level_2_2)
)
AS "Result JSON"
FROM t
GROUP BY level_1_2, level_1_1, level_0

Demo

关于sql - 如何从表中的 oracle sql 中选择带有 group by 子句的嵌套 json 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65104182/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com