Introduction
These functions help you find the first or last value in a group of rows, making it easy to pick important data points without sorting manually.
FIRST_VALUE(column_name) OVER (PARTITION BY group_column ORDER BY order_column [ROWS BETWEEN ...]) LAST_VALUE(column_name) OVER (PARTITION BY group_column ORDER BY order_column [ROWS BETWEEN ...])
SELECT employee_id, department_id, FIRST_VALUE(salary) OVER (PARTITION BY department_id ORDER BY salary DESC) AS highest_salary FROM employees;
SELECT order_id, customer_id, LAST_VALUE(order_date) OVER (PARTITION BY customer_id ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_order_date FROM orders;
CREATE TABLE sales ( id INT, region VARCHAR(10), sale_date DATE, amount INT ); INSERT INTO sales VALUES (1, 'East', '2024-01-01', 100), (2, 'East', '2024-01-05', 150), (3, 'West', '2024-01-03', 200), (4, 'West', '2024-01-10', 250); SELECT region, sale_date, amount, FIRST_VALUE(amount) OVER (PARTITION BY region ORDER BY sale_date) AS first_sale_amount, LAST_VALUE(amount) OVER (PARTITION BY region ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_sale_amount FROM sales ORDER BY region, sale_date;
FIRST_VALUE(column_name) OVER (ORDER BY column_name) return?salary ordered by hire_date in SQL?ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ensures LAST_VALUE looks at the entire partition.sales with columns region and amount, what will this query return?SELECT region, amount, FIRST_VALUE(amount) OVER (PARTITION BY region ORDER BY amount DESC) AS max_amount FROM sales;
SELECT employee_id, LAST_VALUE(salary) OVER (ORDER BY employee_id) AS last_sal FROM employees;
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING makes LAST_VALUE consider all rows.sales table. Which query correctly returns both values on each row?ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING to get true last value.Pass the test and this pattern moves unknown