我有一个包含以下类型的JSON数组的源数据:
[
[
"source 1",
250
],
[
"other source",
58
],
[
"more stuff",
42
],
...
]
可以有1..N对这样的字符串和值。如何从JSON汇总所有值?
答案 0 :(得分:3)
您可以使用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 |
---------------+