Window Functions – SQL
Rankings, running totals, and comparisons with preceding rows – without collapsing groups.
Window functions compute a value over a "window" of related rows, but keep every row. The core is OVER (PARTITION BY ... ORDER BY ...). Available in PostgreSQL (from 8.4), MySQL (from 8.0), and SQLite (from 3.25). The starting point for the following examples is the CTE bestellwert from the previous lesson (order values 1049, 30, 85, 300, 59, 1089).
WITH bw AS (
SELECT b.id, b.kunde_id, b.datum, SUM(bp.menge * p.preis) AS wert
FROM bestellungen b
JOIN bestellpositionen bp ON bp.bestellung_id = b.id
JOIN produkte p ON p.id = bp.produkt_id
GROUP BY b.id, b.kunde_id, b.datum
)
SELECT id, kunde_id, wert,
ROW_NUMBER() OVER (PARTITION BY kunde_id ORDER BY wert DESC) AS rang_beim_kunden,
SUM(wert) OVER (ORDER BY datum, id) AS laufende_summe,
ROUND(100.0 * wert / SUM(wert) OVER (), 1) AS anteil_prozent
FROM bw
ORDER BY datum, id;ROW_NUMBER() numbers without gaps, RANK() assigns the same rank on ties and leaves gaps (1,1,3), DENSE_RANK() leaves no gaps (1,1,2). With LAG()/LEAD() you access the previous/next row – ideal for changes.
-- Change compared to the customer's previous order
SELECT id, kunde_id, datum, wert,
LAG(wert) OVER (PARTITION BY kunde_id ORDER BY datum) AS vorher,
wert - LAG(wert) OVER (PARTITION BY kunde_id ORDER BY datum) AS differenz
FROM bw; -- bw as above, as a CTE
-- Top-1 order per customer (the classic "greatest-n-per-group")
SELECT * FROM (
SELECT bw.*, ROW_NUMBER() OVER (PARTITION BY kunde_id ORDER BY wert DESC) AS rn FROM bw
) t WHERE rn = 1;With the frame you control which rows belong to the window, e.g. a moving average: AVG(wert) OVER (ORDER BY datum ROWS BETWEEN 2 PRECEDING AND CURRENT ROW). Note: with ORDER BY but without a frame, RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW applies – rows with the same sort value (peers) get the same running total.
SELECT and ORDER BY. If you want to filter on them afterwards (WHERE rn = 1), you need a subquery or CTE. The convenient QUALIFY exists only in Snowflake, BigQuery, and DuckDB, not in PostgreSQL, MySQL, or SQLite.