Challenge - 5 Problems
Window Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Calculate running total per department
Given the
sales table with columns department, sale_date, and amount, what is the output of this query?SELECT department, sale_date, amount,
SUM(amount) OVER (PARTITION BY department ORDER BY sale_date) AS running_total
FROM sales
ORDER BY department, sale_date;
SQL
CREATE TABLE sales (department VARCHAR(20), sale_date DATE, amount INT); INSERT INTO sales VALUES ('Electronics', '2024-01-01', 100), ('Electronics', '2024-01-02', 150), ('Clothing', '2024-01-01', 200), ('Clothing', '2024-01-03', 100);
Attempts:
2 left
💡 Hint
Think about how the running total sums amounts within each department ordered by date.
✗ Incorrect
The SUM() OVER (PARTITION BY department ORDER BY sale_date) calculates a running total for each department separately, adding amounts in order of sale_date.
📝 Syntax
intermediate1:30remaining
Identify the syntax error in window function usage
Which option contains a syntax error in using the OVER clause with PARTITION BY?
Attempts:
2 left
💡 Hint
Check the parentheses around the OVER clause.
✗ Incorrect
The OVER clause must be followed by parentheses enclosing PARTITION BY and ORDER BY. Option B misses parentheses causing syntax error.
❓ optimization
advanced2:30remaining
Optimize query with multiple window functions
You want to calculate both the rank and the cumulative sum of sales per region ordered by date. Which query is more efficient?
Attempts:
2 left
💡 Hint
Consider how many times the table is scanned and how partitioning affects results.
✗ Incorrect
Option D calculates both window functions in a single query with correct partitioning and ordering, minimizing scans and producing correct results.
🔧 Debug
advanced2:00remaining
Find the cause of incorrect ranking results
A query uses
RANK() OVER (PARTITION BY department) without ORDER BY. Why might the ranking be incorrect or unexpected?Attempts:
2 left
💡 Hint
Think about what ORDER BY does inside the OVER clause.
✗ Incorrect
RANK() requires ORDER BY inside OVER to define the order for ranking. Without ORDER BY, the ranking is arbitrary and unpredictable.
🧠 Conceptual
expert3:00remaining
Understanding frame specification with PARTITION BY
Consider this query:
What does the frame clause
SELECT department, sale_date, amount,
SUM(amount) OVER (PARTITION BY department ORDER BY sale_date ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS moving_sum
FROM sales
ORDER BY department, sale_date;
What does the frame clause
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW do in this context?Attempts:
2 left
💡 Hint
Think about how the frame defines which rows are included relative to the current row.
✗ Incorrect
The frame clause limits the window to the current row and one row before it, so the sum includes these two rows' amounts per department ordered by sale_date.