Using Window Frame Specification with ROWS BETWEEN in SQL
📖 Scenario: You work for a retail company that wants to analyze sales trends over time. You have a table of daily sales data and want to calculate a running total of sales for each day, considering only the current day and the two previous days.
🎯 Goal: Create a SQL query that uses a window function with a ROWS BETWEEN frame to calculate a 3-day running total of sales.
📋 What You'll Learn
Create a table called
daily_sales with columns sale_date (date) and amount (integer).Insert the exact sales data for five consecutive days as specified.
Write a SQL query that uses
SUM(amount) OVER (ORDER BY sale_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) to calculate the running total.Order the results by
sale_date.💡 Why This Matters
🌍 Real World
Retail companies often analyze sales trends over time to make decisions about inventory and marketing. Running totals help understand recent sales performance.
💼 Career
Knowing how to use window functions with frame specifications is valuable for data analysts and database developers working with time series or ordered data.
Progress0 / 4 steps