Cumulative Genre Revenue, Highest First (Running Total)
Ops wants a Pareto-style view of genre revenue: compute each genre's total revenue, then -- ordered from...
Calculate across related rows without collapsing them: running totals, rankings and month-over-month changes in one query.
Ops wants a Pareto-style view of genre revenue: compute each genre's total revenue, then -- ordered from...
The catalog team wants to segment tracks into 5 equal-sized buckets by duration, longest first, to spot unusually long...
FAQ
Short answers to what people get stuck on most. Tap a question to expand it.
They differ only in how they treat ties.
Track your streak & earn XP
Sign up free to unlock your progress dashboard, daily streaks, and leaderboard ranking.
10 role-based tests for Data Analysts, SQL Developers & Data Engineers with instant scorecards.
A window function computes a value across a set of rows related to the current row without collapsing those rows into one, which is the difference between SUM(amount) OVER (PARTITION BY user_id) and a GROUP BY. That is what makes running totals, per-customer rankings and month-over-month deltas possible in a single pass over the table. Every question below runs against a real database in the browser, so you write the OVER clause and see the result set immediately.
SELECT name, score,
ROW_NUMBER() OVER (ORDER BY score DESC) AS rn,
RANK() OVER (ORDER BY score DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY score DESC) AS dense
FROM results;
-- scores 90, 85, 85, 70
-- rn: 1,2,3,4 rnk: 1,2,2,4 dense: 1,2,2,3WHERE runs before window functions are calculated, so it cannot see their results.
WITH ranked AS (
SELECT customer_id, amount,
ROW_NUMBER() OVER (
PARTITION BY customer_id ORDER BY amount DESC
) AS rn
FROM orders
)
SELECT * FROM ranked WHERE rn = 1;GROUP BY collapses each group to one row. PARTITION BY keeps every row and adds the group's calculation beside it.
SELECT order_id, amount,
SUM(amount) OVER (PARTITION BY customer_id) AS customer_total,
ROUND(100.0 * amount /
SUM(amount) OVER (PARTITION BY customer_id), 1) AS pct
FROM orders;