Skip to content
Quantoros

For 2026: return month (YYYY-MM), repid, that reps revenue, and their RANK within the month by revenue descending. The…

SQLLevel: IntermediateWindow functions

For 2026: return month (YYYY-MM), rep_id, that reps revenue, and their RANK within the month by revenue descending. The rank restarts every month.

Table definitions (from the source exercise):

CREATE TABLE orders(order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, amount REAL, rep_id INTEGER, discount REAL);
Hints
  • Which rows belong to the partition and frame for each current row?
  • Check ordering, ties, frame boundaries and the difference from GROUP BY.

Answer

Approach: GROUP BY month and rep; RANK() OVER (PARTITION BY month ORDER BY SUM(amount) DESC) - a window over an aggregate.

SELECT DATE_FORMAT(order_date, '%Y-%m') AS m, rep_id,
       SUM(amount) AS revenue,
       RANK() OVER (PARTITION BY DATE_FORMAT(order_date, '%Y-%m')
                    ORDER BY SUM(amount) DESC) AS month_rank
FROM orders
WHERE YEAR(order_date) = 2026
GROUP BY m, rep_id;

The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.

Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT

Related questions