Using FIRST_VALUE and LAST_VALUE in SQL
📖 Scenario: You work for a retail company that tracks sales data. You want to find the first and last sale dates for each product to understand sales trends.
🎯 Goal: Create a SQL query that uses FIRST_VALUE and LAST_VALUE window functions to find the first and last sale dates for each product.
📋 What You'll Learn
Create a table called
sales with columns product_id (integer), sale_date (date), and amount (integer).Insert the exact sales data provided.
Write a SQL query that selects
product_id, sale_date, amount, the first sale date per product using FIRST_VALUE(sale_date), and the last sale date per product using LAST_VALUE(sale_date).Use window functions partitioned by
product_id and ordered by sale_date.Ensure the
LAST_VALUE function uses the correct frame clause to get the last sale date per product.💡 Why This Matters
🌍 Real World
Retail companies analyze sales data to understand when products first and last sold, helping with inventory and marketing decisions.
💼 Career
Knowing how to use window functions like FIRST_VALUE and LAST_VALUE is important for data analysts and database developers to write advanced SQL queries.
Progress0 / 4 steps