×

sql · level 2 · unit 5 · lesson 3

  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

Turn a test into a 1 or a 0, then SUM it.

For each game, how many scores were 100 or more, and how many were under 50? WHERE cannot help, because each count needs different rows, side by side.

So give every row a . CASE WHEN points >= 100 THEN 1 ELSE 0 END is 1 for a big score and 0 for any other. The SUM of the flags is how many rows passed.

Each column gets its own CASE, so one query can count as many things as you like, group by group.

SELECT game,
  SUM(CASE WHEN points >= 100 THEN 1 ELSE 0 END) AS big,
  SUM(CASE WHEN points < 50 THEN 1 ELSE 0 END) AS small,
  COUNT(*) AS played
FROM scores
GROUP BY game
ORDER BY game;

COUNT(CASE WHEN points >= 100 THEN 1 END) works too, because COUNT skips the NULLs that a missing ELSE gives.