You are given a table user_transactions containing transaction data with product IDs, spend amounts, and transaction dates.
Task: Calculate the year-on-year growth rate for the total spend for each product.
The result should include:
- year: The year of the transaction
- product_id: The ID of the product
- curr_year_spend: The total spend for the current year
- prev_year_spend: The total spend for the previous year
- yoy_rate: The year-on-year growth rate percentage, rounded to 2 decimal places
The growth rate formula is: ((curr_year_spend - prev_year_spend) / prev_year_spend) * 100
Return results ordered by product_id and year in ascending order.
Table Schema
| Column Name | Type | Description |
|---|---|---|
transaction_id
PK
|
integer | Unique transaction identifier |
product_id
|
integer | Product identifier |
spend
|
decimal | Transaction spend amount |
transaction_date
|
datetime | Date and time of transaction |
Input & Output
| transaction_id | product_id | spend | transaction_date |
|---|---|---|---|
| 1341 | 123424 | 1500.6 | 2019-12-31 12:00:00 |
| 1423 | 123424 | 1000.2 | 2020-12-31 12:00:00 |
| 1623 | 123424 | 1246.44 | 2021-12-31 12:00:00 |
| 1322 | 123424 | 2145.32 | 2022-12-31 12:00:00 |
| year | product_id | curr_year_spend | prev_year_spend | yoy_rate |
|---|---|---|---|---|
| 2019 | 123424 | 1500.6 | ||
| 2020 | 123424 | 1000.2 | 1500.6 | -33.35 |
| 2021 | 123424 | 1246.44 | 1000.2 | 24.62 |
| 2022 | 123424 | 2145.32 | 1246.44 | 72.12 |
Product 123424 shows varying year-over-year growth: a 33.35% decline from 2019 to 2020, 24.62% growth from 2020 to 2021, and 72.12% growth from 2021 to 2022. The first year (2019) has NULL values for previous year and growth rate.
| transaction_id | product_id | spend | transaction_date |
|---|---|---|---|
| 1001 | 100 | 500 | 2020-06-15 10:00:00 |
| 1002 | 100 | 300 | 2021-03-20 14:30:00 |
| 1003 | 200 | 1000 | 2020-08-10 16:45:00 |
| 1004 | 200 | 1200 | 2021-11-05 09:15:00 |
| year | product_id | curr_year_spend | prev_year_spend | yoy_rate |
|---|---|---|---|---|
| 2020 | 100 | 500 | ||
| 2021 | 100 | 300 | 500 | -40 |
| 2020 | 200 | 1000 | ||
| 2021 | 200 | 1200 | 1000 | 20 |
Two products with different growth patterns: Product 100 declined by 40% from 2020 to 2021, while Product 200 grew by 20%. Results are ordered by product_id first, then by year.
Constraints
-
1 ≤ transaction_id ≤ 10000 -
1 ≤ product_id ≤ 1000 -
spendis a positive decimal value -
transaction_dateis a valid datetime