Year-on-Year Spend Growth Rate
Shopify ☯️ Medium SQL
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_id and year in ascending order

Output columns: product_id, year, curr_year_spend, prev_year_spend, yoy_growth_pct

Examples

Example 1:

Input:

user_spend
product_idspendtransaction_dateuser_id
11002021-01-151
1502021-06-201
1802022-03-102
11202022-08-052
21102021-04-121
2652021-11-083
21302022-02-183
21002022-09-252

Output:
curr_year_spendprev_year_spendproduct_idyearyoy_growth_pct
150null12021null
2001501202233.33
175null22021null
2301752202231.43
Quick Solution

Code Environment

Sign in or try as guest to run your code.

Sign In

Track

Question Difficulty Company Access
Need more practice in this area? Explore more questions →