Code24Lab

You are not signed in — the lab works, but your progress is not saved. Sign up

Lesson 1 of 21 is free. Unlock all 21 hands-on labs, the final exam and your certificate.

Buy course — €29.90
Read first

The SQL

SELECT sale_id, rep, amount,
       ROW_NUMBER() OVER (ORDER BY amount DESC) AS rn
FROM sales
ORDER BY rn;

-- top 3 sales: filter the window result in an outer query
SELECT SUM(amount)
FROM (SELECT amount,
             ROW_NUMBER() OVER (ORDER BY amount DESC) AS rn
      FROM sales) AS t
WHERE rn <= 3;
ROW_NUMBER is not deterministic when two rows tie on the ORDER BY columns. In production code add a unique tie-breaker, for example `ORDER BY amount DESC, sale_id`.
Loading the lab…