An aggregate with OVER (ORDER BY …) gives a running total: each row adds up everything up to and including itself. Shipped revenue building up over time:
WITH totals AS (
SELECT o.id, o.ordered_on, SUM(i.qty * p.price) AS total
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN products p ON p.id = i.product_id
WHERE o.status = 'shipped'
GROUP BY o.id, o.ordered_on
)
SELECT ordered_on, total,
SUM(total) OVER (ORDER BY ordered_on) AS running_total
FROM totals
ORDER BY ordered_on;
Which rows count is set by the window's frame. You can name it: ROWS BETWEEN 2 PRECEDING AND CURRENT ROW means this row and the two before it, which gives a moving average over three rows. With only an ORDER BY, the default frame treats rows that tie in the ORDER BY as one step, which surprises people; write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW to go strictly row by row.
SELECT id, ordered_on,
COUNT(*) OVER (ORDER BY ordered_on ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS in_frame,
MIN(ordered_on) OVER (ORDER BY ordered_on ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS frame_starts
FROM orders
ORDER BY ordered_on
LIMIT 4;
LAG(x) reads x from the row before in the window, and LEAD(x) from the row after. The first row's LAG is NULL. They answer "change since last time" questions. Days between each of Ana's and Ben's orders:
SELECT customer_id, ordered_on,
LAG(ordered_on) OVER (PARTITION BY customer_id ORDER BY ordered_on) AS previous,
julianday(ordered_on) - julianday(LAG(ordered_on) OVER (PARTITION BY customer_id ORDER BY ordered_on)) AS days_since
FROM orders
WHERE customer_id IN (1, 2)
ORDER BY customer_id, ordered_on;
LAG(x, 2) looks two rows back, and LAG(x, 1, 0) gives 0 instead of NULL when there's no row. Finally, x / SUM(x) OVER () is each row's share of the whole. Each category's share of all products:
SELECT category, COUNT(*) AS products,
ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS pct
FROM products
GROUP BY category
ORDER BY products DESC, category;