Top 3 Customers by Total Sales (PySpark)

PYSPARK coding challenge · Difficulty: easy · Topic: DataFrame Operations · +50 XP

Problem

Using the PySpark DataFrame API, find the top 3 customers by total sales (sum of amount).

Example Input - `sales`

| order_id | customer_id | product_id | amount | order_date |
| --- | --- | --- | --- | --- |
| 101 | 1 | 11 | 1000 | 2024-01-01 |
| 102 | 1 | 12 | 1500 | 2024-01-03 |
| 103 | 2 | 11 | 800 | 2024-01-02 |
| 104 | 2 | 13 | 450 | 2024-01-05 |
| 105 | 3 | 12 | 980 | 2024-01-04 |
| 106 | 4 | 13 | 760 | 2024-01-06 |

Expected Output

| customer_id | total_sales |
| --- | --- |
| 1 | 2500 |
| 2 | 1250 |
| 3 | 980 |

Notes

What this PYSPARK challenge teaches you

“Top 3 Customers by Total Sales (PySpark)” is a easy-level PYSPARK challenge focused on DataFrame Operations. Working through it gives you hands-on practice with groupBy, agg, orderBy, limit — 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. Aggregate first, then sort, then cut. groupBy gives the totals; orderBy and limit pick the top of them.
  2. groupBy('customer_id').agg(F.sum('amount').alias('total_sales')), then .orderBy(F.col('total_sales').desc()).limit(3).

Where this comes up

Variations of this problem have been reported in interviews at Amazon, Flipkart. Interviewers use it to check whether you can express the logic cleanly and reason about correctness on edge cases such as ties, nulls and empty groups.

How to practise it on PySpark.in

Open the challenge, write your PySpark code 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 PYSPARK challenges

Frequently asked questions

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

No. The PYSPARK 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 easy and covers DataFrame Operations.

Solve this challenge free on PySpark.in