Year-on-Year Spend Growth Rate
Beginner Mode
Objective
Given a table of user spending transactions, calculate the year-on-year growth rate of total spend for each product. Include both the current and previous year's spend, along with the percentage change.
Table Schema:
- user_spend
| Column | Type | Description |
|---|---|---|
| user_id | INTEGER | Unique identifier for the user |
| product_id | INTEGER | Unique identifier for the product |
| spend | DECIMAL | Amount spent on the transaction |
| transaction_date | TIMESTAMP | Date and time of the transaction |
Task Requirements:
- Calculate the total spend for each product per year
- For each product-year combination, include the previous year's total spend
- Compute the year-on-year growth percentage as:
(curr_year_spend - prev_year_spend) / prev_year_spend * 100, rounded to 2 decimal places - For the first year of each product, the previous year's spend and growth percentage should be
NULL - Order results by
product_idandyearin ascending order
Output columns: product_id, year, curr_year_spend, prev_year_spend, yoy_growth_pct
Examples
Example 1:
Output:
Input:
| user_spend | |||
|---|---|---|---|
| product_id | spend | transaction_date | user_id |
| 1 | 100 | 2021-01-15 | 1 |
| 1 | 50 | 2021-06-20 | 1 |
| 1 | 80 | 2022-03-10 | 2 |
| 1 | 120 | 2022-08-05 | 2 |
| 2 | 110 | 2021-04-12 | 1 |
| 2 | 65 | 2021-11-08 | 3 |
| 2 | 130 | 2022-02-18 | 3 |
| 2 | 100 | 2022-09-25 | 2 |
| curr_year_spend | prev_year_spend | product_id | year | yoy_growth_pct |
|---|---|---|---|---|
| 150 | null | 1 | 2021 | null |
| 200 | 150 | 1 | 2022 | 33.33 |
| 175 | null | 2 | 2021 | null |
| 230 | 175 | 2 | 2022 | 31.43 |
Code Environment
Sign in or try as guest to run your code.
Track
| Question | Difficulty | Company | Access |
|---|
Need more practice in this area? Explore more questions →
Shopify