# Window functions aggregate across rows without collapsing them

> GROUP BY collapses each group into one row; a window function such as SUM() OVER (PARTITION BY ... ORDER BY ...) keeps every row and adds the group's running total or rank beside it.

- Question: How do I add a running total or a rank per group in SQL and keep every row?
- Topic: SQL
- Author: Jamal Hansen
- Full post: https://jamalhansen.com/blog/window-functions-the-feature-python-developers-miss-most/
- This page: https://jamalhansen.com/explain/sql/window-functions-keep-every-row/


## In one sentence

`PARTITION BY` is similar to `GROUP BY` since it says which column to focus the activity on, except that it doesn't collapse down the data.

```sql
function() OVER (
    PARTITION BY column    -- Like GROUP BY, but doesn't collapse
    ORDER BY column        -- Order within each partition
)
```

## If you know Python

Pandas handles this reasonably well, though you have to bring back all the data unsummarized for it to do it.

```python
df['running_total'] = df.groupby('customer_id')['amount'].cumsum()
df['rank'] = df.groupby('customer_id')['amount'].rank(ascending=False)
```

Without Pandas, it's quite tedious to loop and summarize the data. Here is the same thing as a window function:

```sql
SELECT *,
       SUM(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running_total,
       RANK() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rank
FROM orders
```

This returns all orders with the cumulative order amount for each customer, by date no less. It also ranks the amount of each purchase against the customer's other purchases.

## The usual mistake

Window functions seem to do aggregation-type activities, so can't `GROUP BY` do this? The short answer is, not very well.

```sql
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
```

That gives one row per customer. But what if you want:
- Each order row, *plus* the customer's running total at that point?
- Each order row, *plus* how it compares to the average?
- Each order row, *plus* its rank within that customer's orders?

`GROUP BY` can't do this, but window functions can. The `ORDER BY` inside `OVER` is the order of the data in the partition. Very important for ranks, and running totals.

## Example

Top 3 orders per customer, combining a CTE with a window function:

```sql
WITH ranked AS (
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn
    FROM orders
)
SELECT * FROM ranked WHERE rn <= 3
```

`LAG()` and `LEAD()` let you reference data from the previous or next row, for example the change since a customer's previous order:

```sql
SELECT customer_id, order_date, amount,
       amount - LAG(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS change
FROM orders
```

## Go deeper

[Window Functions: The Feature Python Developers Miss Most](https://jamalhansen.com/blog/window-functions-the-feature-python-developers-miss-most/), post 16 of [SQL for Python Developers](https://jamalhansen.com/series/sql-for-python-developers/): `ROW_NUMBER`, `RANK` versus `DENSE_RANK`, aggregate functions over a partition, and more examples.

