Computing a moving maximum in BigQuery

后端 未结 3 951
长发绾君心
长发绾君心 2021-01-03 00:18

Given a BigQuery table with some ordering, and some numbers, I\'d like to compute a \"moving maximum\" of the numbers -- similar to a moving average, but for a maximum inste

3条回答
  •  北海茫月
    2021-01-03 00:44

    A trick I'm using for rolling windows: CROSS JOIN with a table of numbers. In this case, to have a moving window of 3 years, I cross join with the numbers 0,1,2. Then you can create an id for each group (ending_at_year==year-i) and group by that.

    SELECT ending_at_year, MAX(mean_temp) max_temp, COUNT(DISTINCT year) c
    FROM 
    (
     SELECT mean_temp, year-i ending_at_year, year
     FROM [publicdata:samples.gsod] a
     CROSS JOIN 
      (SELECT i FROM [fh-bigquery:public_dump.numbers_255] WHERE i<3) b
     WHERE station_number=722860
    )
    GROUP BY ending_at_year
    HAVING c=3
    ORDER BY ending_at_year;
    

提交回复
热议问题