Windows I — ranking & offsets
Concept  ·  SQL & Querying

A window PARTITION returns every row with the aggregate attached; GROUP BY returns one row per group — choosing the wrong one.

Both compute per-group aggregates; the difference is what survives. GROUP BY answers 'one line per shop'; a window answers 'each repair, with its shop's average next to it' — comparisons like mins - AVG(mins) OVER (…) are only possible in the second shape. The mirror failures: needing row-level detail after a GROUP BY (it's gone), or SUMming a windowed aggregate as if it were grouped (it repeats per row).

See it break
repairs
shopmins
east30
east50
west40
The trap
SELECT
  shop,
  AVG(mins) AS avg_mins
FROM
  repairs
GROUP BY
  shop
ORDER BY
  shop;
The fix
SELECT
  shop,
  mins,
  mins - AVG(mins) OVER (
    PARTITION BY
      shop
  ) AS vs_avg
FROM
  repairs
ORDER BY
  shop,
  mins;
The trap
east40
west40
The fix
east30-10
east5010
west400

GROUP BY collapsed the repairs to one row per shop, so the per-repair detail was gone — a window PARTITION keeps every repair with its shop's average attached.

The rule

GROUP BY for one-row-per-group outputs; a window for row-plus-context; never aggregate a window's output without re-grouping deliberately.

Shows up elsewhere
Top-N per groupDefault frame includes peer ties
Try one →Prove it in practice →