Postgres Lag and Lead
The examples provided in "Learning Postgres" for Window Lag/Lead functions in Chapter 6 really don't do a good job of selling you on expending the effort into learning them. Here are some better ones.
Let's say you want to align today's sales totals and yesterday on the same row.
SELECT
sale_date,
sales_amount,
LAG(sales_amount, 1) OVER (ORDER BY sale_date) AS previous_day_sales
FROM
daily_sales;
.. or, you want to know how much more or less today's tally ended at.
SELECT
sale_date,
sales_amount,
LEAD(sales_amount, 1) OVER (ORDER BY sale_date) - sales_amount AS next_day_difference
FROM
daily_sales;
This one is a lot of fun. I have a list of dates. I want to know if there are days missing in that sequence.
SELECT
sale_date,
LEAD(sale_date, 1) OVER (ORDER BY sale_date) AS next_sale_date,
LEAD(sale_date, 1) OVER (ORDER BY sale_date) - sale_date AS gap
FROM
daily_sales;