问题描述
我想计算存储在记录变量中的列的总和。这里是我的变量类型和信息:
我想找到 properties.value.float_value 的总和,其中 properties.key 等于“收入”。我的表名是“userevents”。
如何在 sql(bigquery) 中执行此操作?
解决方法
select sum(p.value.float_value) as float_value_sum
from `userevents`
left join unnest(properties) p
where p.key = 'revenue'
,
您可以使用标量子查询执行此操作,其中获取每一行的部分 SUM
,然后使用外部 SUM
来聚合所有行:
WITH sample_row as (
SELECT [
STRUCT(
STRUCT(
3.14 as float_value,"foo" as string_value,16 as int_value
) as value,"revenue" as key
),STRUCT(
STRUCT(
1.23 as float_value,"bar" as string_value,12 as int_value
) as value,STRUCT(
STRUCT(
6.66 as float_value,"baz" as string_value,99 as int_value
) as value,"stuff" as key
)
] as properties
)
SELECT SUM(
(SELECT SUM(p.value.float_value) FROM UNNEST(properties) as p WHERE p.key = "revenue")
)
FROM sample_row