Bigquery moving average

后端 未结 3 580
遥遥无期
遥遥无期 2021-01-01 07:30

Can anybody tell me how to calculate moving average in bigquery.

Here is what I need in mysql style.

SELECT T1.id, T1.value_column1, avg(T2.value_col         


        
3条回答
  •  借酒劲吻你
    2021-01-01 08:11

    For an updated and more efficient answer, https://stackoverflow.com/a/24943950/132438.


    Check the new LAG() and LEAD() window functions. They allow you to traverse the result set, without the need for a self join.

    https://developers.google.com/bigquery/docs/query-reference#windowfunctions

    A different option with JOIN EACH (this can get too slow as an extremely large amount of data can get generated in the intermediate steps):

    SELECT a.SensorId SensorId, a.Timestamp, AVG(b.Data) AS avg_prev_hour_load
    FROM (
      SELECT * FROM [io_sensor_data.moscone_io13]
      WHERE SensorId = 'XBee_40670EB0/mic') a
    JOIN EACH [io_sensor_data.moscone_io13] b
    ON a.SensorId = b.SensorId
    WHERE b.Timestamp BETWEEN (a.Timestamp - 3600000) AND a.Timestamp
    GROUP BY SensorId, a.Timestamp;
    

    (based on Joe Celko's SQL problems)

提交回复
热议问题