You have access to two tables: Sales and Product.
The Sales table contains information about each sale, including the product sold, user who made the purchase, and quantity bought. The Product table contains the price of each product.
Write a SQL query that finds, for each user, the product(s) on which they spent the most money. If a user spent the same maximum amount on multiple products, return all such products for that user.
Return the result in any order.
Table Schema
| Column Name | Type | Description |
|---|---|---|
sale_id
PK
|
int | Unique sale identifier |
product_id
|
int | Foreign key referencing Product table |
user_id
|
int | User who made the purchase |
quantity
|
int | Quantity of product purchased |
| Column Name | Type | Description |
|---|---|---|
product_id
PK
|
int | Unique product identifier |
price
|
int | Price per unit of the product |
Input & Output
| sale_id | product_id | user_id | quantity |
|---|---|---|---|
| 1 | 1 | 1 | 2 |
| 2 | 3 | 3 | 7 |
| 3 | 1 | 1 | 1 |
| 4 | 2 | 2 | 2 |
| 5 | 2 | 1 | 3 |
| product_id | price |
|---|---|
| 1 | 10 |
| 2 | 25 |
| 3 | 15 |
| user_id | product_id |
|---|---|
| 1 | 2 |
| 2 | 2 |
| 3 | 3 |
User 1 spent: Product 1 = (2+1)*10 = 30, Product 2 = 3*25 = 75. Maximum is Product 2 (75).
User 2 spent: Product 2 = 2*25 = 50. Only product, so it's maximum.
User 3 spent: Product 3 = 7*15 = 105. Only product, so it's maximum.
| sale_id | product_id | user_id | quantity |
|---|---|---|---|
| 1 | 1 | 1 | 3 |
| 2 | 2 | 1 | 2 |
| 3 | 3 | 2 | 1 |
| product_id | price |
|---|---|
| 1 | 20 |
| 2 | 30 |
| 3 | 40 |
| user_id | product_id |
|---|---|
| 1 | 1 |
| 1 | 2 |
| 2 | 3 |
User 1 spent: Product 1 = 3*20 = 60, Product 2 = 2*30 = 60. Both products tie for maximum (60), so both are returned.
User 2 spent: Product 3 = 1*40 = 40. Only product, so it's maximum.
Constraints
-
1 ≤ sale_id, product_id, user_id ≤ 500 -
1 ≤ quantity ≤ 100 -
1 ≤ price ≤ 1000