How do I rank rows within each category using a SQL window function?
SELECT
category,
order_id,
quantity * unit_price AS line_total,
RANK() OVER (PARTITION BY category ORDER BY quantity * unit_price DESC) AS rank_in_group
FROM data
ORDER BY category, rank_in_group;
Run this query in QueryLocal →
`PARTITION BY category` restarts the ranking for every distinct category, while every original row stays in the output — unlike `GROUP BY`, a window function like `RANK()` never collapses rows, it just annotates each one with its position inside its own partition.
A table named data with columns: order_id (integer), customer (text), country (text), category (text), quantity (integer), unit_price (real), order_date (text, YYYY-MM-DD).