Table Schema
Inspect
Table
| Column | Type |
|---|---|
| song_id | integer |
| stream_date | date |
Find songs whose streams increased compared to the previous day.
Table Schema
| Column | Type |
|---|---|
| song_id | integer |
| stream_date | date |
Sample Data
| song_id | stream_date |
|---|---|
| 1 | 2024-01-01 |
| 1 | 2024-01-02 |
| 1 | 2024-01-02 |
| 2 | 2024-01-01 |
| 2 | 2024-01-02 |
| 3 | 2024-01-02 |
| 3 | 2024-01-02 |
| song_id |
|---|
| 1 |
SQL Editor
| song_id |
|---|
| 1 |
Hints
Solution
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
Read the expected output columns to determine the final grain.
Aggregate or rank the input rows to calculate the requested metric.
Filter, sort, and alias the final columns to match the output.
Related Questions