【问题标题】:Aggregation on a window function with minimum windows size在具有最小窗口大小的窗口函数上进行聚合
【发布时间】:2021-12-11 21:39:36
【问题描述】:

假设我有一个收集有序记录的表:

SELECT * FROM items_table ORDER BY day ASC
day total_items
1 5
2 6
3 3
4 1
5 2
6 2
7 4

我希望每 3 天计算一次“total_items”的最大数量,而窗口的大小至少为 3。 如果在特定行的窗口大小不够大,则返回值应为 NULL。

day min_3_days_total_items
1 NULL
2 NULL
3 6
4 6
5 3
6 2
7 4

在 Pandas 中是:

df['total_items'].rolling(3, min_periods=3).max()

如何在 BigQuery SQL 中做到这一点?

【问题讨论】:

    标签: sql google-bigquery window-functions


    【解决方案1】:
    case
      when count(*) over (order by day rows between 2 preceding and current row) = 3
      then max(total_items) over (order by day rows between 2 preceding and current row) end
    

    如果空值只是因为它们出现在列表的开头,您可以类似地基于row_number()lag() 进行测试。我想这取决于你想如何看待数据。如果需要,您当然可以为您的窗口设置别名,如果您更喜欢 if 而不是 case,那么它仍然是等效的。

    我特别假设您在日期编号方面没有空白。如果这些很重要,您可以考虑使用range between 是否更合适。

    https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=96e4e60269535586501da5b9fa70e206

    【讨论】:

      【解决方案2】:

      考虑以下方法

      select *,
        if(count(*) over recent_3_days = 3, 
          max(total_items) over recent_3_days, 
          null) as max_items_in_recent_min_3_days
      from items_table  
      window recent_3_days as (order by day range between 2 preceding and current row)
      order by day
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-13
        • 1970-01-01
        • 2017-09-19
        • 1970-01-01
        • 1970-01-01
        • 2018-08-11
        • 2020-04-27
        相关资源
        最近更新 更多