>_ QueryLocal All recipes
SQL recipe

How do I rank rows within each customer using a SQL window function?

SELECT
  customer,
  order_id,
  quantity * unit_price AS line_total,
  RANK() OVER (PARTITION BY customer ORDER BY quantity * unit_price DESC) AS rank_in_group
FROM data
ORDER BY customer, rank_in_group;
Run this query in QueryLocal →

`PARTITION BY customer` restarts the ranking for every distinct customer, 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).