Quarterly Sales Pivot by Product
SQL coding challenge · Difficulty: medium · Topic: CASE WHEN Pivoting · +100 XP
A retail company wants to analyze their sales performance by product across different quarters. Given a 'sales' table, pivot the quarterly sales amounts by product into separate columns for each quarter. Return product_id, Q1_sales, Q2_sales, Q3_sales, and Q4_sales, ordered by product_id ascending.
Example input
`
sales table:
sales_id | product_id | quarter | amount
1 | 101 | Q1 | 1500.00
2 | 101 | Q2 | 2000.00
3 | 101 | Q3 | 2500.00
4 | 101 | Q4 | 3000.00
5 | 102 | Q1 | 800.00
6 | 102 | Q3 | 1200.00
7 | 103 | Q2 | 500.00
`
Expected output
`
product_id | Q1_sales | Q2_sales | Q3_sales | Q4_sales
101 | 1500.00 | 2000.00 | 2500.00 | 3000.00
102 | 800.00 | 0.00 | 1200.00 | 0.00
103 | 0.00 | 500.00 | 0.00 | 0.00
`
What this SQL challenge teaches you
“Quarterly Sales Pivot by Product” is a medium-level SQL challenge focused on CASE WHEN Pivoting. Working through it gives you hands-on practice with CASE WHEN, pivot, aggregation — 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
- CASE WHEN
- pivot
- aggregation
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 ≤ number of rows ≤ 100,000
- Each product_id appears between 1 and 50 times
- quarter values are one of 'Q1', 'Q2', 'Q3', 'Q4'
- amount values are positive and up to two decimal places
- Return columns: product_id (INTEGER), Q1_sales (DECIMAL), Q2_sales (DECIMAL), Q3_sales (DECIMAL), Q4_sales (DECIMAL), ordered by product_id ASC
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
- Monthly Sales Pivot by Product Type
- Top 3 Products per Category
- Running Total Revenue
- Find Duplicate Emails
- Median Salary per Department
- Second Highest Salary
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 CASE WHEN Pivoting.