ORACLE PLSQL -根据条件将多行的JSON数据合并到单个JSON中

zxlwwiss  于 2023-08-08  发布在  Oracle
关注(0)|答案(1)|浏览(241)

我有一个表,其中列如下

ID         JSON_COL                                                   GROUP
1          { "numbers" : [ 1 , 2 ], alphabets : [ "a" , "b" ] }       1
2          { "numbers" : [ 3 , 4 ], alphabets : [ "c" , "d" ] }       1
3          { "numbers" : [ 5 , 6 ], alphabets : [ "e" , "f" ] }       2
4          { "numbers" : [ 7 , 8 ], alphabets : [ "g" , "h" ] }       2
5          { "numbers" : [ 9 , 10 ], alphabets : [ "i" , "j" ] }      2

字符串
我需要根据组示例将JSON合并为一个:当我根据group = 1进行过滤时,我希望得到以下结果

{ "numbers" : [ 1 , 2, 3, 4 ], alphabets : [ "a" , "b" , "c" , "d" ] }


当我根据group = 2进行过滤时,我期望得到如下结果

{ "numbers" : [ 5 , 6 , 7 , 8 , 9 , 10 ], alphabets : [ "e" , "f" , "g" , "h" , "i" , "j" ] }


请注意,我是PLSQL的初学者,发现很难解决这个问题。我尝试了一些事情,比如
JSON_TRANSFORM,但它有助于合并两个不同的列。但我希望在这里合并同一列的多行。

nkhmeac6

nkhmeac61#

你可以将所有内容聚合到一个数组中,然后使用JSON查询,并让JSON path在每个数组元素中遍历,数组步骤在path之前:[*].path.to.data的。
对于示例数据:

with grp as (
   select
     json_arrayagg(json_col format json) as agg
   from sample s
   where grp = 1
)
select
  json_object(
    key 'numbers' value json_query(
      agg format json,
      '$[*].numbers[*]' returning clob
      with unconditional array wrapper
    ),
    key 'alphabets' value json_query(
      agg format json,
      '$[*].alphabets[*]' returning clob
      with unconditional array wrapper
    )
  ) as result
from grp

字符串
| RESULT |
| ------------ |
| {"numbers":[1,2,3,4],"alphabets":["a","b","c","d"]} |
fiddle

相关问题