Window functions

Analyzing Business Data in SQL

Michel Semaan

Data Scientist

Window functions - overview

  • Window functions: Perform an operation across a set of rows related to the current row
  • Examples
    • Calculate a running total
    • Fetch the value of a previous or following row
Analyzing Business Data in SQL

Running total

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
Analyzing Business Data in SQL

Registrations running total - query

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;
Analyzing Business Data in SQL

Registrations running total - result

delivr_month  regs  regs_rt
------------  ----  -------
2018-06-01    123    123
2018-07-01    140    263
2018-08-01    157    420
Analyzing Business Data in SQL

Lagged MAU - query

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;
Analyzing Business Data in SQL

Lagged MAU - result

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

Window functions

Analyzing Business Data in SQL

Preparing Video For Download...