简体   繁体   中英

Bigquery - Window function - Sum over last 3 months

I am looking to sum a column over the last 3 months using WINDOW function.

An example of what my data structure is as follows

Date Customer_id Amount

01-01-2020 A 100.0

01-02-2020 A 100.0

01-03-2020 A 100.0

01-04-2020 A 100.0....

My current approach is to create a WINDOW function as follows:

WINDOW
90d_rolling AS (PARTITION BY customer_id ORDER BY date ROWS BETWEEN 89 PRECEDING AND CURRENT ROW)

This proxies 3 months as 90 days - but I was wondering if it is possible to sum over last 3 months USING A WINDOW FUNCTION ie for the date of 01-04-2020 -> it would sum up till 01-01-2020.

Note that I know that a way of doing this is via

left join to itself where a.date >= date_sub(b.date, interval 3 month) and a.date <= b.date

(but i am just curious if there is a another way)

Below is for BigQuery Standard SQL

#standardSQL
SELECT *, 
  SUM(amount) OVER(
    PARTITION BY customer_id 
    ORDER BY DATE_DIFF(`date`, '2000-01-01', MONTH)
    RANGE BETWEEN 3 PRECEDING AND 1 PRECEDING
  ) AS rolling_3m_ammount
FROM `project.dataset.table`

Note: based sample data in your question and comments - I assume all dates are first day of month!

You can test, play with above using sample/dummy data as in below example

#standardSQL
WITH `project.dataset.table` AS (
  SELECT DATE '2020-01-01' `date`, 'A' customer_id, 1.0 amount UNION ALL
  SELECT '2020-02-01', 'A', 2.0 UNION ALL
  SELECT '2020-03-01', 'A', 3.0 UNION ALL
  SELECT '2020-04-01', 'A', 4.0 UNION ALL
  SELECT '2020-05-01', 'A', 5.0 UNION ALL
  SELECT '2020-07-01', 'A', 6.0 UNION ALL
  SELECT '2020-09-01', 'A', 7.0 
)
SELECT *, 
  SUM(amount) OVER(
    PARTITION BY customer_id 
    ORDER BY DATE_DIFF(`date`, '2000-01-01', MONTH)
    RANGE BETWEEN 3 PRECEDING AND 1 PRECEDING
  ) AS rolling_3m_ammount
FROM `project.dataset.table`
-- ORDER BY `date`   

with output

Row date        customer_id amount  rolling_3m_ammount   
1   2020-01-01  A           1.0     null     
2   2020-02-01  A           2.0     1.0  
3   2020-03-01  A           3.0     3.0  
4   2020-04-01  A           4.0     6.0  
5   2020-05-01  A           5.0     9.0  
6   2020-07-01  A           6.0     9.0  
7   2020-09-01  A           7.0     6.0  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM