SQL window functions: running totals and rankings

asked 2 months ago152 viewsen

0

I need a running total of sales per month, and the top 3 products per category. Currently I do it in Python after fetching everything. Can SQL do this directly?

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

1 Answer

6
✓
✓ Accepted answer

Yes, with window functions. They compute over a set of rows *without collapsing them* like GROUP BY does.

Running total:

SELECT month,
       revenue,
       SUM(revenue) OVER (ORDER BY month) AS running_total
FROM monthly_sales;

Top 3 per category:

SELECT *
FROM (
  SELECT category, product, revenue,
         ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) AS rn
  FROM product_sales
) t
WHERE rn <= 3;

- PARTITION BY restarts the calculation per group. - ROW_NUMBER gives unique ranks; RANK/DENSE_RANK handle ties. - LAG(revenue) OVER (ORDER BY month) gives the previous row, handy for month-over-month growth.

Window functions run in the database, next to the data, which is usually far faster than shipping all rows to Python.

Sign in to tell others whether this worked.

answered 2 months ago

Sign in and verify your email to post an answer.