Middle
Mis on LAG ja LEAD?
sobes.tech AI
Vastus AI-lt
LAG and LEAD are window functions in SQL that allow you to retrieve the value from another row relative to the current row within a defined window (set of rows).
- LAG returns the value from the previous row (backward shift).
- LEAD returns the value from the next row (forward shift).
They are useful for comparing the current row with neighboring rows, for example, to calculate the difference between values or to analyze trends.
Example:
SELECT
date,
sales,
LAG(sales, 1) OVER (ORDER BY date) AS prev_day_sales,
LEAD(sales, 1) OVER (ORDER BY date) AS next_day_sales
FROM sales_data;