SQL
Lab
Spotify Spotify Interview Question 08

Trending
Songs

Find songs whose streams increased compared to the previous day.

Table Schema

Inspect
Table

interactive
ColumnType
song_idinteger
stream_datedate

Sample Data

Input
Output

Sample Input: streams
song_idstream_date
12024-01-01
12024-01-02
12024-01-02
22024-01-01
22024-01-02
32024-01-02
32024-01-02
Expected Output
song_id
1

SQL Editor

Run
Query

postgresql
Waiting for query

song_id
1

Hints

Unlock
Clues

Hint 01: Identify the grouping level required by the output.
Hint 02: Aggregate with COUNT, SUM, AVG, or a window function as needed.
Hint 03: Filter after aggregation with HAVING or after ranking with an outer query.

Solution

Locked
Answer

Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.

WITH daily_counts AS (
  SELECT song_id, stream_date, COUNT(*) AS frequency
  FROM streams
  GROUP BY song_id, stream_date
),
with_previous AS (
  SELECT
    song_id,
    stream_date,
    frequency,
    LAG(frequency) OVER (PARTITION BY song_id ORDER BY stream_date) AS previous_frequency
  FROM daily_counts
)
SELECT DISTINCT song_id
FROM with_previous
WHERE frequency > previous_frequency;

Explanation

Step By
Step

01

Read the expected output columns to determine the final grain.

02

Aggregate or rank the input rows to calculate the requested metric.

03

Filter, sort, and alias the final columns to match the output.

Related Questions

Keep
Solving