Premium problem33. Listening History With Running Total

Medium Locked

streams(user_id, song_id, listened_at, seconds_played)

For each stream, in chronological order within a user, return that stream plus cumulative_seconds: everything the user has listened to up to and including it. Where two streams share a timestamp, the lower song_id comes first.

Return user_id, listened_at, song_id, seconds_played and cumulative_seconds, in that same order.

The running total restarts for each user rather than carrying across.

Tables

streams

user_id  song_id  listened_at          seconds_played
-------  -------  -------------------  --------------
10       101      2026-04-01 10:00:00  120
10       103      2026-04-01 11:00:00  60
10       102      2026-04-01 11:00:00  30
10       104      2026-04-02 09:00:00  200
11       201      2026-04-01 08:00:00  45
11       202      2026-04-03 08:00:00  55

Expected result

user_id  listened_at          song_id  seconds_played  cumulative_seconds
-------  -------------------  -------  --------------  ------------------
10       2026-04-01 10:00:00  101      120             120
10       2026-04-01 11:00:00  102      30              150
10       2026-04-01 11:00:00  103      60              210
10       2026-04-02 09:00:00  104      200             410
11       2026-04-01 08:00:00  201      45              45
11       2026-04-03 08:00:00  202      55              100

Premium problem

This one's part of Premium. Unlock the full MySQL track plus every other premium problem on the site.

Write one SELECT query