Complete the code to select the previous salary using LAG function.
SELECT employee_id, salary, LAG(salary) OVER (ORDER BY employee_id) AS previous_salary FROM employees WHERE department_id = [1];The department_id is a number, so use 10 without quotes to filter correctly.
Complete the code to get the previous order date for each customer.
SELECT customer_id, order_date, LAG(order_date) OVER (ORDER BY [1]) AS previous_order FROM orders;Ordering by order_date ensures the previous order date is the correct previous row.
Fix the error in the LAG function usage to get previous sales amount per region.
SELECT region, sales_date, LAG(sales_amount) OVER (PARTITION BY [1] ORDER BY sales_date) AS prev_sales FROM sales_data;Partitioning by region groups rows by region to get previous sales within each region.
Fill both blanks to calculate the difference between current and previous salary per department.
SELECT employee_id, salary, LAG(salary) OVER (PARTITION BY [1] ORDER BY [2]) AS prev_salary, salary - LAG(salary) OVER (PARTITION BY [1] ORDER BY [2]) AS salary_diff FROM employees;
Partition by department_id to group employees by department. Order by hire_date to get previous salary in hire order.
Fill all three blanks to get previous and next order dates per customer and calculate gap days.
SELECT customer_id, order_date, LAG(order_date) OVER (PARTITION BY [1] ORDER BY [2]) AS prev_order, LEAD(order_date) OVER (PARTITION BY [1] ORDER BY [2]) AS next_order, DATEDIFF(day, LAG(order_date) OVER (PARTITION BY [1] ORDER BY [2]), order_date) AS days_since_prev FROM orders;
Partition by customer_id to group orders per customer. Order by order_date to get previous and next orders chronologically. Use order_date in DATEDIFF to calculate days difference.