8/34
Part 2 of 6 · RankingLearn and do
RANK and DENSE_RANK keep ties at the cutoff, so pick the function your question means
Rank the amounts with RANK instead of ROW_NUMBER, and a top 2 comes back as three rows, because both 45s rank 2:
WITH ranked AS (
SELECT order_id, amount,
RANK() OVER (ORDER BY amount DESC) AS rnk
FROM orders
)
SELECT order_id, amount, rnk
FROM ranked
WHERE rnk <= 2
ORDER BY rnk, order_id;
| order_id | amount | rnk |
|---|---|---|
| 7 | 50 | 1 |
| 3 | 45 | 2 |
| 6 | 45 | 2 |
Here is the same cutoff, <= 2, under each of the three:
| Order | Amount | ROW_NUMBER, tie-break by id | RANK | DENSE_RANK |
|---|---|---|---|---|
| #7 | 50 | 1, kept | 1, kept | 1, kept |
| #3 | 45 | 2, kept | 2, kept | 2, kept |
| #6 | 45 | 3, cut | 2, kept | 2, kept |
| #5 | 35 | 4, cut | 4, cut | 3, cut |
| Rows kept | 2 | 3 | 3 |
Neither function is wrong. They answer different questions:
- The two largest, ties to the lower id: ROW_NUMBER with the id in the ORDER BY.
- Every order tied for a top-2 spot: RANK.
- Every order at one of the two highest amounts: DENSE_RANK.
RANK and DENSE_RANK split when the tie is at the top:
A and B tie for first, and C has the next amount. Keep <= 2:
| RANK | DENSE_RANK | |
|---|---|---|
| A | 1, kept | 1, kept |
| B | 1, kept | 1, kept |
| C | 3, cut | 2, kept |
Both tied orders get RANK 1, and the next one gets 3, so rank <= 2 stops at the pair. DENSE_RANK gives the next amount a 2 and keeps it.
In the editor, write TOP_TWO_AMOUNTS: every order at one of the two highest amounts, the third question in the list.