[英]Summing values from a JSON array in Snowflake
I have a source data which contains the following type of a JSON array: 我有一个包含以下类型的JSON数组的源数据:
[
[
"source 1",
250
],
[
"other source",
58
],
[
"more stuff",
42
],
...
]
There can be 1..N pairs of strings and values like this. 可以有1..N对这样的字符串和值。 How can I sum all the values together from this JSON? 如何将这个JSON中的所有值加在一起?
You can use FLATTEN , it will produce a single row for each element of the input array. 您可以使用FLATTEN ,它将为输入数组的每个元素产生一行。 Then you can access the number in that element directly. 然后,您可以直接访问该元素中的数字。
Imagine you have this input table: 假设您有此输入表:
create or replace table input as
select parse_json($$
[
[
"source 1",
250
],
[
"other source",
58
],
[
"more stuff",
42
]
]
$$) as json;
FLATTEN will do this: FLATTEN将执行以下操作:
select index, value from input, table(flatten(json));
-------+-------------------+
INDEX | VALUE |
-------+-------------------+
0 | [ |
| "source 1", |
| 250 |
| ] |
1 | [ |
| "other source", |
| 58 |
| ] |
2 | [ |
| "more stuff", |
| 42 |
| ] |
-------+-------------------+
And so you can just use VALUE[1]
to access what you want 因此,您只需使用VALUE[1]
即可访问所需内容
select sum(value[1]) from input, table(flatten(json));
---------------+
SUM(VALUE[1]) |
---------------+
350 |
---------------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.