All problems

Who Are Our Top Viewers, Ranked?

hardSQLWindow Functions

StreamVerse's engagement team is building a viewer leaderboard for an internal dashboard. A single "most active subscriber" badge was the first version and it turned out to be useless: it never changed, and it said nothing about how far ahead the leader actually was. This time they want the whole board — every subscriber, their total, and their position on it.

The awkward part is that the position depends on a number that does not exist yet. Nobody's total watch time is stored; it is spread across however many sessions they logged, three for one subscriber and one for another. The positions can only be worked out once those totals exist.

watch_events — one row per viewing session. subscriber_id is the subscriber who watched. watch_minutes is how long that session lasted.

id subscriber_id show_id watch_minutes watch_date
1 1 1 45 2023-05-01
2 1 5 60 2023-05-03
3 2 3 20 2023-05-02
4 3 2 55 2023-05-05
5 4 1 40 2023-05-06
6 4 4 70 2023-05-08
7 1 3 25 2023-05-10
8 3 5 50 2023-05-11
9 2 2 30 2023-05-12
10 5 4 65 2023-05-14

The table already exists in the database — there is nothing to create or load.

Task: Write a query returning three columns, subscriber_id, total_minutes and viewer_rank, with one row per subscriber who has logged at least one session. total_minutes is that subscriber's minutes across all their sessions. viewer_rank is their position on the board, 1 for the highest total. Two subscribers on exactly the same total share a position, and the position straight after it is skipped, so a board can read 1, 2, 2, 4. A subscriber with no sessions at all does not appear. Rows come back sorted by viewer_rank, best position first, and two subscribers sharing a position by subscriber_id.

Example output — shape only, on an invented board; the two subscribers level on 180 minutes show the shared position and the skip that follows it.

subscriber_id total_minutes viewer_rank
6 300 1
7 180 2
9 180 2
8 95 4

Sign in to solve this problem

Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.

Sign in

Discussion

Sign in to join the discussion — reading is open to everyone.

Loading comments…