Window Functions
Window Functions perform calculations across a subset of rows (called a "window") that are defined relative to the current row. They allow you to perform operations like ranking, running totals, and differences between rows, all while retaining individual rows in the result set.
SELECT
customer_id,
purchase_date,
amount,
SUM(amount) OVER (PARTITION BY customer_id ORDER BY purchase_date) AS running_total
FROM
purchase_data;
- SUM(amount) calculates a running total for each customer.
- OVER (PARTITION BY customer_id ORDER BY purchase_date) defines the "window" of rows over which the calculation is performed, grouped by customer_id and ordered by purchase_date.