BigQuery - Moving median calculation

前端 未结 1 1235
旧时难觅i
旧时难觅i 2021-01-25 14:13

I have data on monthly sales like this

Company  Month    Sales
Adidas   2018-09   100
Adidas   2018-08    95
Adidas   2018-07   120
Adidas   2018-06   155
...and         


        
相关标签:
1条回答
  • 2021-01-25 14:54

    Here is an approach that might work:

    CREATE TEMP FUNCTION MEDIAN(arr ANY TYPE) AS ((
      SELECT
        IF(
          MOD(ARRAY_LENGTH(arr), 2) = 0,
          (arr[OFFSET(DIV(ARRAY_LENGTH(arr), 2) - 1)] + arr[OFFSET(DIV(ARRAY_LENGTH(arr), 2))]) / 2,
          arr[OFFSET(DIV(ARRAY_LENGTH(arr), 2))]
        )
      FROM (SELECT ARRAY_AGG(x ORDER BY x) AS arr FROM UNNEST(arr) AS x)
    ));
    
    SELECT
      Company,
      Month,
      MEDIAN(
        ARRAY_AGG(Sales) OVER (PARTITION BY Company ORDER BY Month ROWS BETWEEN 11 PRECEDING AND CURRENT ROW)
      ) AS trailing_median
    FROM (
      SELECT 'Adidas' AS Company, '2018-09' AS Month, 100 AS Sales UNION ALL
      SELECT 'Adidas', '2018-08', 95 UNION ALL
      SELECT 'Adidas', '2018-07', 120 UNION ALL
      SELECT 'Adidas', '2018-06', 155
    );
    

    The results are:

    +---------+---------+-----------------+
    | Company |  Month  | trailing_median |
    +---------+---------+-----------------+
    | Adidas  | 2018-06 |           155.0 |
    | Adidas  | 2018-07 |           137.5 |
    | Adidas  | 2018-08 |           120.0 |
    | Adidas  | 2018-09 |           110.0 |
    +---------+---------+-----------------+
    
    0 讨论(0)
提交回复
热议问题