Introduction
The LAG function helps you look at the value from the previous row in a table. It is useful when you want to compare current data with past data in a list.
LAG(column_name, offset, default_value) OVER (ORDER BY column_to_order)
SELECT LAG(sales) OVER (ORDER BY month) AS prev_month_sales FROM sales_data;
SELECT LAG(score, 2, 0) OVER (ORDER BY test_date) AS score_two_tests_ago FROM tests;
SELECT employee, salary, LAG(salary) OVER (ORDER BY employee_id) AS prev_salary FROM employees;
CREATE TABLE sales_data (month VARCHAR(10), sales INT); INSERT INTO sales_data VALUES ('Jan', 100), ('Feb', 150), ('Mar', 130), ('Apr', 170); SELECT month, sales, LAG(sales) OVER (ORDER BY month) AS prev_month_sales FROM sales_data;
LAG function do?LAG to get the previous salary ordered by employee ID?Employees with columns id and salary, what will this query return?SELECT id, salary, LAG(salary) OVER (ORDER BY id) AS prev_salary FROM Employees;
id | salary
1 | 5000
2 | 6000
3 | 5500SELECT id, salary, LAG(salary) ORDER BY id AS prev_salary FROM Employees;
id. Which query correctly calculates this difference?Pass the test and this pattern moves unknown