Definição
Acessa o valor de uma linha anterior dentro da partição. Base de comparações com o período anterior.
Exemplos
1. Valor do dia anterior
SELECT dt, amount,
LAG(amount) OVER (ORDER BY dt) AS previous_amount
FROM daily_sales;2. Variação percentual mês a mês
SELECT month, total,
(total - LAG(total) OVER (ORDER BY month))
/ LAG(total) OVER (ORDER BY month) AS variation
FROM monthly_summary;3. Detectar mudança de status
SELECT order_id, ts, status
FROM (SELECT h.*, LAG(status) OVER (
PARTITION BY order_id ORDER BY ts) AS previous
FROM history h) t
WHERE status <> previous OR previous IS NULL;