×

sql · level 3 · unit 2 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A adds a group answer without squashing rows.

GROUP BY squashes rows: ten orders become one total. Sometimes you want to keep every order and see the total beside it. A window function does that. It looks across many rows, but it gives an answer on every row.

Add after an aggregate to turn it into a window function. Empty brackets, OVER (), make the window the whole result. So SUM(total) OVER () puts the grand total beside every order.

With the total on each row, you can compare across rows, such as each order's share of the takings.

SELECT id, total,
  SUM(total) OVER () AS all_orders,
  ROUND(100.0 * total / SUM(total) OVER (), 1) AS pct
FROM orders
ORDER BY id;

The window sees the rows left after WHERE, not the whole table.