You want to find the first and last sale amounts per customer ordered by sale date from the sales table. Which query correctly returns both values on each row?
hard📝 Application Q15 of 15
SQL - Advanced Window Functions
You want to find the first and last sale amounts per customer ordered by sale date from the sales table. Which query correctly returns both values on each row?
ASELECT customer_id, sale_date, FIRST_VALUE(amount) OVER (PARTITION BY customer_id ORDER BY sale_date) AS first_sale, LAST_VALUE(amount) OVER (PARTITION BY customer_id ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_sale FROM sales;
BSELECT customer_id, sale_date, FIRST_VALUE(amount) OVER (ORDER BY sale_date) AS first_sale, LAST_VALUE(amount) OVER (ORDER BY sale_date) AS last_sale FROM sales;
CSELECT customer_id, sale_date, FIRST_VALUE(amount) AS first_sale, LAST_VALUE(amount) AS last_sale FROM sales GROUP BY customer_id;
DSELECT customer_id, sale_date, MIN(amount) OVER (PARTITION BY customer_id) AS first_sale, MAX(amount) OVER (PARTITION BY customer_id) AS last_sale FROM sales;
Step-by-Step Solution
Solution:
Step 1: Use PARTITION BY customer_id
This groups rows by customer to get first and last sales per customer.
Step 2: Use ORDER BY sale_date for chronological order
Ordering by sale_date ensures first and last are by date.
Step 3: Add frame clause for LAST_VALUE
LAST_VALUE needs ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING to get true last value.
Final Answer:
Query in option A correctly returns first and last sale amounts per customer -> Option A
Quick Check:
FIRST_VALUE and LAST_VALUE with proper frame and partition [OK]
Quick Trick:Use full frame for LAST_VALUE with PARTITION and ORDER BY [OK]
Common Mistakes:
Omitting frame clause for LAST_VALUE
Using aggregate functions instead of window functions
Not partitioning by customer_id
Master "Advanced Window Functions" in SQL
9 interactive learning modes - each teaches the same concept differently