【问题标题】:How to accumulate for previous 7 days value in BigQuery?如何在 BigQuery 中累积前 7 天的值?
【发布时间】:2021-06-10 11:44:17
【问题描述】:

在 BigQuery SQL 中,如何累积某个时期的值?

我有一张这样的桌子。 我想获得每行前 7 天的总和。

请让我知道对此的查询。

Date Value
2021-05-10 3
2021-05-11 1
2021-05-14 2
2021-05-15 0
2021-05-16 3
2021-05-17 1
2021-05-18 1
2021-05-20 1
2021-05-23 1
2021-05-28 1
... ...

预期

Date Value acc_7
2021-05-10 3 3 (Sum of 05-04 ~ 05-10)
2021-05-11 1 4 (Sum of 05-05 ~ 05-11)
2021-05-14 2 6 (Sum of 05-08 ~ 05-14)
2021-05-15 0 6 (Sum of 05-09 ~ 05-15)
2021-05-16 3 9 (Sum of 05-10 ~ 05-16)
2021-05-17 1 7 (Sum of 05-11 ~ 05-17)
2021-05-18 1 7 (Sum of 05-12 ~ 05-18)
2021-05-20 1 8 (Sum of 05-14 ~ 05-20)
2021-05-23 1 4 (Sum of 05-17 ~ 05-23)
2021-05-28 1 2 (Sum of 05-22 ~ 05-28)
... ... ...

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    您可以使用range 窗框,但您需要将日期转换为天数。

    select t.*,
           sum(value) over (order by unix_date(date)
                            range between 6 preceding and current row
                           ) as value_7
    from t;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多