Bigquery moving average

后端 未结 3 578
遥遥无期
遥遥无期 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 07:45

    I have created the following "Times" table:

    Table Details: Dim_Periods
    Schema
    Date    TIMESTAMP   
    Year    INTEGER         
    Month   INTEGER         
    day         INTEGER         
    QUARTER INTEGER     
    DAYOFWEEK   INTEGER     
    MonthStart  TIMESTAMP   
    MonthEnd    TIMESTAMP   
    WeekStart   TIMESTAMP   
    WeekEnd TIMESTAMP   
    Back30Days  TIMESTAMP   -- the date 30 days before "Date"
    Back7Days   TIMESTAMP   -- the date 7 days before "Date"
    

    and I use such query to handle "running sums"

    SELECT Date,Count(*) as MovingCNT
    FROM
    
    (SELECT Date,
                    Back7Days 
                        FROM DWH.Dim_Periods  
                     where Date < timestamp(current_date()) AND
                                 Date >= (DATE_ADD (CURRENT_TIMESTAMP(), -5, 'month'))
                    )P
                    CROSS JOIN EACH
        (SELECT repository_url,repository_created_at
        FROM publicdata:samples.github_timeline
                    ) L
            WHERE timestamp(repository_created_at)>= Back7Days 
                  AND timestamp(repository_created_at)<= Date
    
    GROUP EACH BY Date
    

    Note that it can be used for "Month to date", Week to Date" "30 days back" etc. aggregations as well. However, performance is not the best and the query can take a while on larger data sets due to the Cartesian join. Hope this helps

提交回复
热议问题