Best Selling Month of Each Year

SQL coding challenge · Difficulty: medium · Topic: Window Functions · +100 XP

Problem

For each year, find the month that sold the most.

One row per year — not the single best month overall, and not every month. 2023's best month was month 2 with 700; 2024's was month 3 with 900.

Schema — `month_sales`

| Column | Type |
| --- | --- |
| sales_year | INT |
| month_num | INT |
| sales | INT |

Example Input — `month_sales`

| sales_year | month_num | sales |
| --- | --- | --- |
| 2023 | 1 | 500 |
| 2023 | 2 | 700 |
| 2023 | 3 | 650 |
| 2024 | 1 | 800 |
| 2024 | 2 | 750 |
| 2024 | 3 | 900 |

Expected Output

| sales_year | month_num | sales |
| --- | --- | --- |
| 2023 | 2 | 700 |
| 2024 | 3 | 900 |

Explanation

A plain MAX(sales) grouped by year gives you the number but loses the month it belongs to, which is the part being asked for.

Notes

What this SQL challenge teaches you

“Best Selling Month of Each Year” is a medium-level SQL challenge focused on Window Functions. Working through it gives you hands-on practice with ROW_NUMBER, PARTITION BY, Subquery, Top-N — the kind of transformation you are asked to write in real data engineering work and in technical interviews. You can solve it directly in the browser: the dataset is pre-loaded, so you write the query or DataFrame code, run it, and compare your output against the expected result immediately.

Concepts covered

How to approach it

If you get stuck, work through these steps in order before looking at a full solution — each one narrows the problem down:

  1. ROW_NUMBER() OVER (PARTITION BY sales_year ORDER BY sales DESC) ranks months within each year.
  2. A window function cannot be used in WHERE, so rank in a subquery and filter outside it.
  3. Keep the rows where the rank is 1.

How to practise it on PySpark.in

Open the challenge, write your SQL query in the editor and press Run to execute it against the sample dataset. Submitting checks your output against every test case, including hidden ones, so you find out straight away whether your logic holds up. You can retry as often as you like, and each solved challenge adds to your XP.

Related SQL challenges

Frequently asked questions

Do I need to install Spark or a database to solve this?

No. The SQL environment runs in your browser with the sample data already loaded, so there is nothing to install or configure.

Is this challenge free?

Yes - the problem, the sample dataset, the hints and unlimited test runs are free.

What level is it?

It is rated medium and covers Window Functions.

Solve this challenge free on PySpark.in