You are given three related tables: Salesperson, Customer, and Sales. Your task is to calculate the total sales influence of each salesperson by summing up all the sales made by their customers.
Write a SQL query to return the sum of prices paid by the customers of each salesperson. If a salesperson has no customers or their customers made no sales, the total should be 0.
Key Points:
- Each salesperson can have multiple customers
- Each customer can make multiple sales
- Include all salespeople in the result, even those with no sales
- Return results in any order
Table Schema
| Column Name | Type | Description |
|---|---|---|
salesperson_id
PK
|
int | Unique identifier for each salesperson |
name
|
varchar | Name of the salesperson |
| Column Name | Type | Description |
|---|---|---|
customer_id
PK
|
int | Unique identifier for each customer |
salesperson_id
|
int | Foreign key referencing Salesperson table |
| Column Name | Type | Description |
|---|---|---|
sale_id
PK
|
int | Unique identifier for each sale |
customer_id
|
int | Foreign key referencing Customer table |
price
|
int | Price paid for the sale |
Input & Output
| salesperson_id | name |
|---|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Jerry |
| customer_id | salesperson_id |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 2 |
| sale_id | customer_id | price |
|---|---|---|
| 1 | 1 | 500 |
| 2 | 2 | 1000 |
| 3 | 2 | 250 |
| salesperson_id | name | total |
|---|---|---|
| 1 | Alice | 1750 |
| 2 | Bob | 0 |
| 3 | Jerry | 0 |
Alice has customers 1 and 2. Customer 1 made 1 sale ($500), customer 2 made 2 sales ($1000 + $250). Alice's total: $1750. Bob has customer 3 but no sales recorded, so total is $0. Jerry has no customers, so total is $0.
| salesperson_id | name |
|---|---|
| 1 | John |
| 2 | Amy |
| customer_id | salesperson_id |
|---|---|
| 1 | 1 |
| sale_id | customer_id | price |
|---|---|---|
| 1 | 1 | 2500 |
| salesperson_id | name | total |
|---|---|---|
| 1 | John | 2500 |
| 2 | Amy | 0 |
John has customer 1 who made a sale of $2500. Amy has no customers, so her total is $0. The LEFT JOIN ensures Amy still appears in the result.
| salesperson_id | name |
|---|---|
| 1 | Mike |
| 2 | Sarah |
| customer_id | salesperson_id |
|---|
| sale_id | customer_id | price |
|---|
| salesperson_id | name | total |
|---|---|---|
| 1 | Mike | 0 |
| 2 | Sarah | 0 |
No customers or sales exist in the database, but all salespeople must still appear in the result with total = 0, demonstrating the importance of LEFT JOIN.
Constraints
-
1 ≤ salesperson_id ≤ 10^5 -
1 ≤ customer_id ≤ 10^5 -
1 ≤ sale_id ≤ 10^5 -
1 ≤ price ≤ 10^4 - All IDs are unique within their respective tables