With Spark SQL, find the best-selling product(s) of every region by total revenue (SUM(amount)). If products tie for the top revenue in a region, return all of them. Ignore rows with a NULL region or product.
| order_id | customer_id | region | product | qty | amount | order_date |
|---|---|---|---|---|---|---|
| 1 | 101 | North | Laptop | 1 | 55000.0 | 2024-01-05 |
| 2 | 102 | South | Mobile | 2 | 30000.0 | 2024-01-07 |
| 3 | 101 | North | Keyboard | 1 | 1500.0 | 2024-02-02 |
| 4 | 103 | East | Monitor | 1 | 18000.0 | 2024-02-10 |
| 5 | 104 | South | Headphones | 3 | 6000.0 | 2024-03-01 |
| region | product | revenue |
|---|---|---|
| East | Monitor | 18000 |
| North | Laptop | 55000 |
| South | Mobile | 30000 |
| order_id | customer_id | region | product | qty | amount | order_date |
|---|---|---|---|---|---|---|
| 1 | 1 | West | Mobile | 1 | 500.0 | 2024-01-01 |
| 2 | 2 | West | Laptop | 1 | 300.0 | 2024-01-01 |
| 3 | 3 | West | Laptop | 1 | 300.0 | 2024-01-02 |
| region | product | revenue |
|---|---|---|
| West | Laptop | 600 |
Return columns region, product, revenue. Row order does not matter. Use spark.sql.
Solve it in the live editor on this page — run on sample data, then submit against hidden tests.
‹ City Revenue Including Cities with No Orders · Employees Above Their Department Average ›
{{ totalCount }} questions · {{ shHardPct }}% Hard. Real PySpark DataFrame and Spark SQL interview questions. Write PySpark in your browser on TechTown’s Spark engine, run sample tests, then submit against hidden tests.
Guests can solve {{ freeLimit }} problems for free. Log in or sign up (free) to unlock everything, keep your streak and appear on the leaderboard. New to a topic? Learn it first in the Spark course.
{{ p.statement }}
{{ p.constraints }}
No submissions yet. Press Submit to judge your code against all tests.
The model solution and step-by-step explanation unlock when you solve this problem or after 3 unsuccessful submissions ({{ shFailsLabel }}). Struggling? Try the hints on the Question tab first.
{{ p.solution }}
Write real PySpark: from pyspark.sql import functions as F, Window, spark.sql(...). It runs in your browser on a lightweight Spark engine, and the same code runs unchanged on Databricks or any Spark cluster. Use df.show() or print() to debug.
Create your free TechTown account to unlock every problem, track your progress, bookmark questions and keep preparing for interviews.