You are given two tables: Products and Purchases.
The Products table contains product information with unique product IDs and their unit prices.
The Purchases table contains invoice details showing the quantity of each product ordered in different invoices.
Write a SQL query to find the details of the invoice with the highest total price. If multiple invoices have the same highest price, return the one with the smallest invoice_id.
Return the result showing each product in that invoice with columns: product, quantity, price (unit price), and price * quantity (total for that product).
Table Schema
| Column Name | Type | Description |
|---|---|---|
product_id
PK
|
int | Unique product identifier |
price
|
int | Unit price of the product |
| Column Name | Type | Description |
|---|---|---|
invoice_id
PK
|
int | Invoice identifier |
product_id
PK
|
int | Product identifier (foreign key) |
quantity
|
int | Quantity of product ordered |
Input & Output
| product_id | price |
|---|---|
| 1 | 10 |
| 2 | 25 |
| 3 | 15 |
| 4 | 2 |
| invoice_id | product_id | quantity |
|---|---|---|
| 1 | 1 | 12 |
| 1 | 2 | 3 |
| 2 | 2 | 10 |
| 2 | 4 | 15 |
| 3 | 3 | 1 |
| product | quantity | price | total |
|---|---|---|---|
| 2 | 10 | 25 | 250 |
| 4 | 15 | 2 | 30 |
Invoice totals: Invoice 1 = (12×10 + 3×25) = 195, Invoice 2 = (10×25 + 15×2) = 280, Invoice 3 = (1×15) = 15. Invoice 2 has the highest total (280), so we return its product details.
| product_id | price |
|---|---|
| 1 | 20 |
| 2 | 50 |
| invoice_id | product_id | quantity |
|---|---|---|
| 3 | 1 | 5 |
| 1 | 2 | 2 |
| product | quantity | price | total |
|---|---|---|---|
| 2 | 2 | 50 | 100 |
Invoice totals: Invoice 1 = (2×50) = 100, Invoice 3 = (5×20) = 100. Both have the same total, but invoice 1 has the smaller invoice_id, so we return invoice 1's details.
Constraints
-
1 ≤ product_id ≤ 1000 -
1 ≤ price ≤ 1000 -
1 ≤ invoice_id ≤ 1000 -
1 ≤ quantity ≤ 1000