【问题标题】:Get array size in oracle sql在oracle sql中获取数组大小
【发布时间】:2020-07-29 09:35:40
【问题描述】:

我在 oracle 中有一个具有此定义的表


    create table PARAM(
       ID VARCHAR(30),
       DOCUMENT   blob
    )

Document以json格式存储。

{"id":"value","parameters":[{...},{...},{...}]}

如何在sql中提取数组参数的大小?

我需要为每个表记录提取数组大小,然后对所有这些值求和。

例如:

1 步:


    ID    ARRAY_SIZE
    ----  ----------
    1     10
    2     0
    3     3

2 步:


    TOTAL_RECORDS   TOTAL_ARRAYS_SIZE
    -------------   -----------------
    3               13

有人可以告诉我怎么做吗?

【问题讨论】:

  • 您使用的是什么版本的 Oracle?
  • Oracle Database 19c 企业版 19.0 版

标签: sql arrays json oracle


【解决方案1】:

如果你对列有is json检查约束,你可以使用size()方法获取数组中的数字元素:

create table t (
  c1 int, 
  c2 varchar2(100) 
    check ( c2 is json ) 
);

insert into t values ( 1, '{ "arr" : [1, 2, 3] }');
insert into t values ( 2, '{ "arr" : [1, 2, 3, 4, 5] }');

select c1, t.c2.arr.size() from t t;

C1    T.C2.ARR.SIZE()   
 1                  3 
 2                  5 

【讨论】:

  • 这适用于哪个版本的 Oracle? Oracle 18 db<>fiddle 不起作用。
  • 18c;您可以将其与json_value ( c2, '$.arr.size()' ) 一起使用。不确定点符号的问题是什么
【解决方案2】:

对于 blob 字段的情况,我看到以下决定。

你有一张类似这样的桌子

create table tmp_js
(
   id       number,
   document blob  
);

带有 json 对象的表看起来像这样

ID    Document 
----  ----------
1     {"id": 1, "paramters": [{"t": 2}, {"t": 3}]}
2     {"id": 2, "paramters": [{"t": 2}, {"t": 3}, {"t": 4}]}
3     {"id": 3, "paramters": [{"t": 2}, {"t": 3}, {"t": 5}, {"t": 6}]}

然后您可以通过以下方式解决您的任务

第 1 步

您将在行的文档中获得行的 id 和数组的大小。

select
    t.id,            
    (select
        count(*)
    from
        json_table(json_query(t.document, '$.paramters'), '$[*]' columns (value path '$.t'))
    ) as cnt       
from
    tmp_js t

第二步

您可以根据第一步的结果进行汇总。

select
    count(*),
    sum(cnt)
from    
    (select
        t.id,            
        (select
            count(*)
        from
            json_table
            (
                json_query(t.document, '$.paramters'), 
                '$[*]' columns (value path '$.t')
            )
        ) as cnt       
    from
        tmp_js t)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 2011-01-18
    相关资源
    最近更新 更多