Moving averages and share of total
A moving average smooths out a bumpy series. Tell the window exactly which rows to include with a frame:
AVG(revenue) OVER (
ORDER BY month
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS moving_avg_3For each month, that averages it with the two months before: a 3-month moving average. At the start of the series there aren't two earlier months yet, so the first rows average whatever is there (one month, then two).
ROWS BETWEEN 6 PRECEDING AND CURRENT ROWover days is a 7-day average.ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWis everything so far (a running total).
An empty OVER () means "all the rows", which makes share of total easy:
SELECT category, revenue,
100.0 * revenue / SUM(revenue) OVER () AS pct_of_total
FROM category_revenueROWS or RANGE? Without a frame,
SUM(…) OVER (ORDER BY x)usesRANGE, which treats rows with the samexas one step. Whenxis unique (one row per month) it makes no difference. When it isn't, add a tie-breaker or writeROWSso you know what you're getting.