Given two tables Product and Sales, write a SQL query to report the total sales amount of each item for each year.
The Product table contains basic product information, while the Sales table contains sales periods with average daily sales amounts. Each sales period can span multiple years (2018-2020), so you need to calculate how much was sold in each individual year.
Return the result with columns: product_name, product_id, report_year, and total_amount.
Note: Sales periods are inclusive of both start and end dates. If a period spans multiple years, split the sales proportionally by the number of days in each year.
Table Schema
| Column Name | Type | Description |
|---|---|---|
product_id
PK
|
int | Primary key, unique identifier for each product |
product_name
|
varchar | Name of the product |
| Column Name | Type | Description |
|---|---|---|
product_id
PK
|
int | Foreign key referencing Product table |
period_start
|
date | Start date of sales period (inclusive) |
period_end
|
date | End date of sales period (inclusive) |
average_daily_sales
|
int | Average daily sales amount during the period |
Input & Output
| product_id | product_name |
|---|---|
| 1 | LC Phone |
| 2 | LC T-Shirt |
| 3 | LC Keychain |
| product_id | period_start | period_end | average_daily_sales |
|---|---|---|---|
| 1 | 2019-01-25 | 2019-02-28 | 100 |
| 2 | 2018-12-01 | 2020-01-01 | 10 |
| 3 | 2019-12-01 | 2020-01-31 | 1 |
| product_name | product_id | report_year | total_amount |
|---|---|---|---|
| LC Phone | 1 | 2019 | 3500 |
| LC T-Shirt | 2 | 2018 | 310 |
| LC T-Shirt | 2 | 2019 | 3650 |
| LC T-Shirt | 2 | 2020 | 10 |
| LC Keychain | 3 | 2019 | 31 |
| LC Keychain | 3 | 2020 | 31 |
LC Phone sold from 2019-01-25 to 2019-02-28 (35 days in 2019): 35 × 100 = 3500. LC T-Shirt period spans multiple years: 31 days in 2018, 365 days in 2019, 1 day in 2020. LC Keychain spans 2019 (31 days) and 2020 (31 days).
| product_id | product_name |
|---|---|
| 1 | LC Phone |
| product_id | period_start | period_end | average_daily_sales |
|---|---|---|---|
| 1 | 2018-01-01 | 2018-12-31 | 5 |
| product_name | product_id | report_year | total_amount |
|---|---|---|---|
| LC Phone | 1 | 2018 | 1825 |
Simple case where the entire sales period falls within a single year 2018. Total days: 365, so total amount = 365 × 5 = 1825.
Constraints
-
1 ≤ Product.product_id ≤ 1000 -
1 ≤ Sales.product_id ≤ 1000 -
Sales.period_startandperiod_endare between 2018-01-01 and 2020-12-31 -
period_start ≤ period_end -
1 ≤ average_daily_sales ≤ 100