Analyzing Business Data in SQL
Michel Semaan
Data Scientist
Running total: A cumulative sum of a variable's previous values
Example
x x_rt
--- ----
1 1
2 3
3 6
4 11
5 16
WITH reg_dates AS ( SELECT user_id, MIN(order_date) AS reg_date FROM orders GROUP BY user_id),
registrations AS ( SELECT DATE_TRUNC('month', reg_date) :: DATE AS delivr_month, COUNT(DISTINCT user_id) AS regs FROM reg_dates GROUP BY delivr_month)
SELECT delivr_month, regs, SUM(regs) OVER (ORDER BY delivr_month ASC) AS regs_rt FROM registrations ORDER BY delivr_month ASC LIMIT 3;
delivr_month regs regs_rt
------------ ---- -------
2018-06-01 123 123
2018-07-01 140 263
2018-08-01 157 420
WITH maus AS ( SELECT DATE_TRUNC('month', order_date) :: DATE AS delivr_month, COUNT(DISTINCT user_id) AS mau FROM orders GROUP BY delivr_month)
SELECT delivr_month, mau, COALESCE( LAG(mau) OVER (ORDER BY delivr_month ASC), 1) AS last_mau FROM maus ORDER BY delivr_month ASC LIMIT 3;
delivr_month mau last_mau
------------ --- --------
2018-06-01 123 1
2018-07-01 226 123
2018-08-01 337 226
Analyzing Business Data in SQL