📖 Scenario: You are working as a data analyst for a retail company. You have a table called sales that records each sale transaction with columns for sale_id, store_id, sale_date, and amount. Your manager wants to analyze sales trends by store and over time.
🎯 Goal: Build a PostgreSQL query using window functions to calculate the running total of sales amount per store ordered by sale date, and also rank each sale within its store by amount.
📋 What You'll Learn
Use the sales table with columns sale_id, store_id, sale_date, and amount
Calculate a running total of amount per store_id ordered by sale_date
Rank each sale within its store_id by amount in descending order
Use window functions SUM() OVER() and RANK() OVER()
💡 Why This Matters
🌍 Real World
Retail analysts often need to track cumulative sales and rank transactions to identify top-performing stores or sales days.
💼 Career
Understanding window functions is essential for data analysts and database professionals to perform advanced data analysis and reporting.
Progress0 / 4 steps
1
Create the sales table and insert sample data
Write SQL statements to create a table called sales with columns sale_id (integer), store_id (integer), sale_date (date), and amount (numeric). Then insert these exact rows: (1, 101, '2024-01-01', 100.00), (2, 101, '2024-01-02', 150.00), (3, 102, '2024-01-01', 200.00), (4, 101, '2024-01-03', 50.00), (5, 102, '2024-01-02', 300.00).
PostgreSQL
Hint
Use CREATE TABLE to define the table and INSERT INTO to add rows with exact values.
2
Define the window partition and order for running total
Write a SQL query selecting all columns from sales. Add a window function SUM(amount) OVER (PARTITION BY store_id ORDER BY sale_date) and alias it as running_total to calculate the running total of sales amount per store ordered by sale date.
PostgreSQL
Hint
Use SUM(amount) OVER (PARTITION BY store_id ORDER BY sale_date) to get the running total per store.
3
Add ranking of sales by amount within each store
Extend the previous query by adding a new column that uses the window function RANK() OVER (PARTITION BY store_id ORDER BY amount DESC) and alias it as sale_rank. This ranks sales within each store by amount from highest to lowest.
PostgreSQL
Hint
Use RANK() OVER (PARTITION BY store_id ORDER BY amount DESC) to rank sales by amount within each store.
4
Complete the query with ordering by store and sale date
Add an ORDER BY store_id, sale_date clause at the end of the query to display results sorted by store and then by sale date.
PostgreSQL
Hint
Use ORDER BY store_id, sale_date to sort the final output by store and date.
Practice
(1/5)
1. What does the ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) window function do in a query?
easy
A. Counts the number of employees in each department.
B. Assigns a unique rank to each employee within their department based on salary, starting at 1 for the highest salary.
C. Calculates the total salary for each department.
D. Returns the average salary of all employees.
Solution
Step 1: Understand ROW_NUMBER() with PARTITION BY
The function assigns a unique sequential number to rows within each department group.
Step 2: ORDER BY salary DESC ranks highest salary first
Ordering by salary descending means the highest salary gets row number 1 in each department.
Final Answer:
Assigns a unique rank to each employee within their department based on salary, starting at 1 for the highest salary. -> Option B
Quick Check:
ROW_NUMBER() with PARTITION BY and ORDER BY = ranked rows [OK]
Hint: ROW_NUMBER() numbers rows per group ordered by criteria [OK]
Common Mistakes:
Confusing ROW_NUMBER() with COUNT() or SUM()
Ignoring PARTITION BY and thinking it ranks globally
Assuming it calculates totals or averages
2. Which of the following is the correct syntax to calculate a running total of sales ordered by date using window functions in PostgreSQL?
easy
A. SELECT date, sales, SUM(sales) PARTITION BY date FROM sales_data;
B. SELECT date, sales, SUM(sales) GROUP BY date ORDER BY running_total FROM sales_data;
C. SELECT date, sales, SUM(sales) WHERE ORDER BY date FROM sales_data;
D. SELECT date, sales, SUM(sales) OVER (ORDER BY date) AS running_total FROM sales_data;
Solution
Step 1: Identify correct window function syntax
SUM(sales) OVER (ORDER BY date) calculates running total by ordering rows by date.
Step 2: Check other options for syntax errors
The incorrect options misuse PARTITION BY without OVER(), use WHERE incorrectly, or confuse GROUP BY with window functions.
Final Answer:
SELECT date, sales, SUM(sales) OVER (ORDER BY date) AS running_total FROM sales_data; -> Option D
Quick Check:
SUM() OVER (ORDER BY ...) = running total syntax [OK]
Hint: Use OVER() with ORDER BY for running totals [OK]
Common Mistakes:
Using PARTITION BY without OVER()
Trying to use WHERE inside window function
Confusing GROUP BY with window functions
3. Given the table sales(date, amount) with rows: ('2024-01-01', 100), ('2024-01-02', 150), ('2024-01-03', 200) What is the output of this query?
SELECT date, amount, SUM(amount) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total FROM sales ORDER BY date;
medium
A. [('2024-01-01', 100, 450), ('2024-01-02', 150, 350), ('2024-01-03', 200, 200)]
B. [('2024-01-01', 100, 100), ('2024-01-02', 150, 150), ('2024-01-03', 200, 200)]
C. [('2024-01-01', 100, 100), ('2024-01-02', 150, 250), ('2024-01-03', 200, 450)]
D. [('2024-01-01', 100, NULL), ('2024-01-02', 150, NULL), ('2024-01-03', 200, NULL)]
Solution
Step 1: Understand SUM() OVER with frame
The frame includes all rows from the start up to current row ordered by date, so it sums cumulatively.
Hint: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW sums cumulatively [OK]
Common Mistakes:
Ignoring frame clause and expecting total sum on all rows
Confusing running total with simple SUM() aggregation
Assuming NULLs appear without reason
4. You wrote this query to rank employees by salary within each department:
SELECT employee_id, department, salary, RANK() OVER (ORDER BY salary DESC) AS dept_rank FROM employees;
But the query returns the same rank for all employees regardless of department. What is the likely mistake?
medium
A. Missing PARTITION BY clause inside OVER()
B. ORDER BY salary ASC instead of DESC
C. Using RANK() instead of ROW_NUMBER()
D. Not ordering the final result by department
Solution
Step 1: Check PARTITION BY usage
If PARTITION BY is missing or incorrect, ranking happens over entire table, ignoring departments.
Step 2: Confirm ORDER BY and function choice
ORDER BY DESC is correct for highest salary first; RANK() is appropriate for ties; ordering final result doesn't affect ranking.
Final Answer:
Missing PARTITION BY clause inside OVER() -> Option A
Quick Check:
PARTITION BY groups rows for ranking [OK]
Hint: Always include PARTITION BY to rank within groups [OK]
Common Mistakes:
Forgetting PARTITION BY causes global ranking
Confusing RANK() and ROW_NUMBER() effects
Thinking ORDER BY outside OVER() affects ranking
5. You want to find each employee's salary difference compared to the previous employee in the same department ordered by salary descending. Which query correctly uses window functions to achieve this?
hard
A. SELECT employee_id, department, salary, salary - LAG(salary) OVER (PARTITION BY department ORDER BY salary DESC) AS salary_diff FROM employees;
B. SELECT employee_id, department, salary, salary - LEAD(salary) OVER (ORDER BY salary) AS salary_diff FROM employees;
C. SELECT employee_id, department, salary, salary - LAG(salary) FROM employees GROUP BY department ORDER BY salary DESC;
D. SELECT employee_id, department, salary, salary - FIRST_VALUE(salary) OVER (PARTITION BY department) AS salary_diff FROM employees;
Solution
Step 1: Use LAG() to get previous row's salary per department
LAG(salary) OVER (PARTITION BY department ORDER BY salary DESC) gets previous salary in descending order within department.
Step 2: Subtract previous salary from current salary
salary - LAG(salary) calculates difference compared to previous employee.
Final Answer:
SELECT employee_id, department, salary, salary - LAG(salary) OVER (PARTITION BY department ORDER BY salary DESC) AS salary_diff FROM employees; -> Option A
Quick Check:
LAG() gets previous row value for difference [OK]
Hint: Use LAG() with PARTITION BY and ORDER BY for previous row values [OK]
Common Mistakes:
Using LEAD() instead of LAG() for previous row
Omitting PARTITION BY causing wrong grouping
Trying to use aggregate functions without OVER()
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.