×

sql · level 3 · unit 4 · lesson 2

  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

Make a of dates, then join the real data onto it.

The café has no row for 4 June, so reports skip that day and averages mislead. Fix it with a series: every date from the first day to the last, made by a recursive CTE. date(day, '+1 day') gives the next date.

Then LEFT JOIN the takings onto the series. Days with no takings get NULL, because nothing matched them.

swaps that NULL for 0. It gives back the first of its values that is not NULL, so a missing day becomes a day that took nothing.

WITH RECURSIVE days(day) AS (
  SELECT '2024-06-01'
  UNION ALL
  SELECT date(day, '+1 day') FROM days WHERE day < '2024-06-08'
)
SELECT d.day, COALESCE(t.amount, 0) AS amount
FROM days AS d
LEFT JOIN takings AS t ON t.day = d.day
ORDER BY d.day;

Dates written as YYYY-MM-DD sort and compare correctly as text.