【问题标题】:SQL Using record variablesSQL 使用记录变量
【发布时间】:2021-09-21 00:13:20
【问题描述】:

我想计算存储在记录变量中的列的总和。这是我的变量类型和信息:

我想找到 properties.value.float_value 的总和,其中 properties.key 等于“收入”。我的表名是“userevents”。

如何在 SQL(bigquery) 中执行此操作?

【问题讨论】:

  • 您的问题不清楚。您想要每行还是所有行的总和。

标签: sql google-bigquery key unnest


【解决方案1】:
select sum(p.value.float_value) as float_value_sum
from `userevents`
left join unnest(properties) p
where p.key = 'revenue'

【讨论】:

    【解决方案2】:

    您可以使用标量子查询来执行此操作,您可以在其中获取每行的部分 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,
                "revenue" as key
            ),
            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
    

    【讨论】:

      猜你喜欢
      • 2010-09-24
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多