Window Functions

GROUP BY collapses each group into one row. A window function keeps the rows as they are and attaches, next to each row, a result computed over the group (window) that row belongs to.

function(...) OVER (PARTITION BY grouping_column ORDER BY order_column frame)
PartMeaning
PARTITION BYThe criterion that divides windows. Without it, the whole set is one window
ORDER BYThe order within the window. Needed for ranks, running totals, and previous/next-row calculations
FrameThe range of rows within the window included in the calculation (ROWS BETWEEN …)

Window functions are computed in the SELECT step, after WHERE, GROUP BY, and HAVING finish. So they cannot be used in WHERE; to filter on their results, wrap the query once in an inline view or WITH.

Aggregate functions as windows

Customer's total order count and amount share per order

SELECT ord_id, cust_id, amt,
       COUNT(*) OVER (PARTITION BY cust_id)                 AS cust_orders,
       SUM(amt) OVER (PARTITION BY cust_id)                 AS cust_total,
       ROUND(100.0 * amt / SUM(amt) OVER (PARTITION BY cust_id), 1) AS pct
FROM orders
WHERE cust_id IN (101, 102)
ORDER BY cust_id, ord_id

Ranking: ROW_NUMBER, RANK, DENSE_RANK

FunctionOn equal valuesExample (values 100, 90, 90, 80)
ROW_NUMBER()Different numbers (order not determined)1, 2, 3, 4
RANK()Same rank, skips the next rank1, 2, 2, 4
DENSE_RANK()Same rank, no skipping1, 2, 2, 3

Rank customers 101-120 by order count

SELECT cust_id, COUNT(*) AS orders,
       ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) AS row_num,
       RANK()       OVER (ORDER BY COUNT(*) DESC) AS rnk,
       DENSE_RANK() OVER (ORDER BY COUNT(*) DESC) AS dense_rnk
FROM orders
WHERE cust_id BETWEEN 101 AND 120
GROUP BY cust_id
ORDER BY orders DESC, cust_id

Because GROUP BY finishes first, you can rank by an aggregate result, as in OVER (ORDER BY COUNT(*)).

Top N per group

Assign ROW_NUMBER, then filter outside. Rows with the groupwise maximum compares ways to solve the same problem with subqueries and joins.

Two largest orders per customer

WITH ranked AS (
  SELECT ord_id, cust_id, amt,
         ROW_NUMBER() OVER (PARTITION BY cust_id ORDER BY amt DESC, ord_id) AS rn
  FROM orders
  WHERE cust_id BETWEEN 101 AND 105
)
SELECT cust_id, ord_id, amt, rn
FROM ranked
WHERE rn <= 2
ORDER BY cust_id, rn

Running totals and moving averages: the frame

The default frame of an aggregate window with ORDER BY is "from the start to the current row". ROWS BETWEEN sets the range explicitly.

Running amount and average of the last 3 orders

SELECT ord_id, ord_dt, amt,
       SUM(amt) OVER (ORDER BY ord_dt, ord_id
                      ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total,
       AVG(amt) OVER (ORDER BY ord_dt, ord_id
                      ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)         AS moving_avg_3
FROM orders
WHERE cust_id = 101
ORDER BY ord_dt, ord_id

NOTE When the frame is omitted, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE includes all rows with the same sort key at once, so if the sort key has duplicates, the result differs from ROWS. Specify ROWS for running totals.

Previous and next rows: LAG, LEAD

Gap from the previous order

SELECT ord_id, ord_dt, amt,
       LAG(ord_dt) OVER (ORDER BY ord_dt, ord_id) AS prev_dt,
       LAG(amt)    OVER (ORDER BY ord_dt, ord_id) AS prev_amt,
       amt - LAG(amt) OVER (ORDER BY ord_dt, ord_id) AS diff_amt,
       LEAD(ord_dt) OVER (ORDER BY ord_dt, ord_id) AS next_dt
FROM orders
WHERE cust_id = 101
ORDER BY ord_dt, ord_id

LAG on the first row and LEAD on the last row are NULL. A third argument supplies a substitute value, as in LAG(amt, 1, 0).

FIRST_VALUE, LAST_VALUE

Compare with the customer's first order amount

SELECT ord_id, ord_dt, amt,
       FIRST_VALUE(amt) OVER (ORDER BY ord_dt, ord_id) AS first_amt,
       LAST_VALUE(amt)  OVER (ORDER BY ord_dt, ord_id
                              ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_amt
FROM orders
WHERE cust_id = 101
ORDER BY ord_dt, ord_id

The default frame for LAST_VALUE ends at the current row, so unless the frame is widened, it always returns the current row's value.

Bucketing, percentiles, and ratios are covered in Distribution and ratios; grouping consecutive values or dates into a single range is covered in Finding consecutive ranges.