Calculate Total Sales and Average Order Value by Customer

PYSPARK coding challenge · Difficulty: medium · +100 XP

Each row of the orders DataFrame is a single order placed by a customer.

Input

A DataFrame named orders with columns order_id, customer_id, and order_value:

| order_id | customer_id | order_value |
| --- | --- | --- |
| 1 | 101 | 250.0 |
| 2 | 102 | 300.0 |
| 3 | 101 | 150.0 |
| 4 | 103 | 400.0 |
| 5 | 102 | 200.0 |
| 6 | 101 | 350.0 |
| 7 | 103 | 100.0 |

Task

For each customer_id, compute:

  • total_sales — the sum of order_value
  • avg_order_value — the average of order_value

Return a DataFrame with columns customer_id, total_sales, avg_order_value.

Expected output

| customer_id | total_sales | avg_order_value |
| --- | --- | --- |
| 101 | 750.0 | 250.0 |
| 102 | 500.0 | 250.0 |
| 103 | 500.0 | 250.0 |

Solve this challenge on PySpark.in