AlgoMaster Logo

Exercise: Window Functions

Last Updated: May 12, 2026

1 min read

For this exercise, we will work with below data:

SQL

Exercise 1

Easy

For each stream, return stream_iduser_idduration_listened, and the total duration_listened across all streams as total_duration. Use a window function, not a subquery. Order by stream_id.

SQL

Expected Query

Expected Output

Exercise 2

Easy

For each stream by user_id 1, return stream_idduration_listened, and that user's total listening time as user_total. Order by stream_id.

SQL

Expected Query

Expected Output

Exercise 3

Medium

For each completed payment by user_id 4, return payment_idpayment_dateamount, and a running total of amount ordered by payment_date as running_total. Order by payment_date.

SQL

Expected Query

Expected Output

Exercise 4

Medium

Write a window-function query that returns every stream row with an extra column country_streams showing the total number of streams from that stream's country. Use OVER (PARTITION BY country). Show stream_iduser_idcountry, and country_streams. Order by country (NULLs last), then stream_id.

SQL

Expected Query

Expected Output

Exercise 5

Medium

For each stream by user_id 2, return stream_idstarted_atduration_listened, and the running total of duration_listened ordered by started_at as running_total. Order by started_at.

SQL

Expected Query

Expected Output

Exercise 6

Hard

Find every completed payment whose user has a total completed-payment amount greater than 25.00. Return payment_iduser_idamount, and user_total. Order by payment_id.

SQL

Expected Query

Expected Output

Exercise 7

Hard

Compare partition-wide totals to running totals using the same data. For each stream by user_id 1, return stream_idstarted_atduration_listened, the user's total listening time as user_total, and the running total of duration_listened ordered by started_at as running_total. Order by started_at.

SQL

Expected Query

Expected Output