I’m trying to solve this:
You’ve been given a database for an online streaming service that first released in 2020. The database has a table customers
with a column net_new
that records net new monthly subscriptions to the streaming service broken down by tiers: free, standard, and premium.
Write a SELECT
statement using windows functions to calculate two new columns from net_new
:
total
: this column should contain a running total count of customers partitioned by the three subscription tiersyear_over_year
: for each month, this column should subtract thenet_new
value 12 months earlier from the currentnet_new
value. This calculation should also be partitioned bylevel
. Use the default LAG behavior for the first 12 months (2020), which will be null.
Your final SELECT
query should have the columns year
, month
, level
, total
, and year_over_year
in that order. Do not apply any additional order by
statements, other than the ones needed within the window functions to properly perform the calculation.
My solution is this:
SELECT
year,
month,
level,
SUM(net_new) OVER (PARTITION BY level ORDER BY year, month) AS total,
net_new - LAG(net_new, 12) OVER (PARTITION BY level ORDER BY year, month) AS year_over_year
FROM
customers
ORDER BY
year, month, level;
I couldn’t solve it because according to Codecademy there is something wrong. The output is this:
Not quite! Check that your columns are in the right order, and that you’ve used SUM
and LAG
with the correct window syntax.