对 Snowflake 中的 JSON 数组中的值求和

问题描述 投票:0回答:2

我有一个源数据,其中包含以下类型的 JSON 数组:

[
  [
    "source 1",
    250    
  ],
  [
    "other source",
    58
  ],
  [
    "more stuff",
    42
  ],
  ...
]

可以有 1..N 对这样的字符串和值。如何将这个 JSON 中的所有值加在一起?

json snowflake-cloud-data-platform snowsql
2个回答
4
投票

您可以使用FLATTEN,它将为输入数组的每个元素生成一行。然后您可以直接访问该元素中的数字。

假设您有这个输入表:

create or replace table input as
select parse_json($$
[
  [
    "source 1",
    250    
  ],
  [
    "other source",
    58
  ],
  [
    "more stuff",
    42
  ]
]
$$) as json;

FLATTEN 会这样做:

select index, value from input, table(flatten(json));
-------+-------------------+
 INDEX |       VALUE       |
-------+-------------------+
 0     | [                 |
       |   "source 1",     |
       |   250             |
       | ]                 |
 1     | [                 |
       |   "other source", |
       |   58              |
       | ]                 |
 2     | [                 |
       |   "more stuff",   |
       |   42              |
       | ]                 |
-------+-------------------+

因此您可以使用

VALUE[1]
来访问您想要的内容

select sum(value[1]) from input, table(flatten(json));
---------------+
 SUM(VALUE[1]) |
---------------+
 350           |
---------------+

0
投票

使用高阶函数

REDUCE
:

SELECT col, REDUCE(col, 0, (acc, x) -> acc + x[1]::NUMBER) AS col_sum
FROM tab;

输入:

CREATE OR REPLACE TABLE tab(col VARIANT)
AS
SELECT [
  ['source 1', 250 ],
  ['other source',58],
  ['more stuff',42]
];

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.