October 11, 2026
SQL notes · clinical toy data · every day on the calendar, zeros included
The idea. Real event tables have gaps — no row exists for days
nothing happened. A plain GROUP BY day then lies by omission:
quiet days vanish instead of showing zero. The fix is a date spine
(a complete calendar you build yourself), optionally crossed with your categories,
with the events LEFT JOINed on.
ed_visits — January has 31 days; only 3 of them have visits
| visit_date | department |
|---|---|
| 2024-01-02 | ER |
| 2024-01-02 | ER |
| 2024-01-04 | Cardiology |
| 2024-01-07 | ER |
SELECT visit_date AS day, COUNT(*) AS visits FROM ed_visits GROUP BY visit_date ORDER BY day;
| day | visits |
|---|---|
| 2024-01-02 | 2 |
| 2024-01-04 | 1 |
| 2024-01-07 | 1 |
Three rows. The other 28 days of January simply don't exist here — any chart drawn from this is missing most of the month.
WITH RECURSIVE spine(d) AS (
SELECT date('2024-01-01')
UNION ALL
SELECT date(d, '+1 day') FROM spine WHERE d < '2024-01-31'
)\nSELECT d FROM spine; -- 31 rows
Start at Jan 1, keep adding a day until Jan 31. (Dialect note: BigQuery spells this
GENERATE_DATE_ARRAY; the idea is identical.)
WITH RECURSIVE spine(d) AS (
SELECT date('2024-01-01')
UNION ALL
SELECT date(d, '+1 day') FROM spine WHERE d < '2024-01-31'
),
depts AS (SELECT DISTINCT department AS dept FROM ed_visits)
SELECT s.d, x.dept FROM spine s CROSS JOIN depts x ORDER BY s.d, x.dept;
CROSS JOIN is the full multiplication: 31 days × 2 departments =
62 rows. This grid is the skeleton your facts hang on.
WITH RECURSIVE spine(d) AS (
SELECT date('2024-01-01')
UNION ALL
SELECT date(d, '+1 day') FROM spine WHERE d < '2024-01-31'
),
depts AS (SELECT DISTINCT department AS dept FROM ed_visits)
SELECT s.d AS day, x.dept AS department, COUNT(v.visit_date) AS visits
FROM spine s CROSS JOIN depts x
LEFT JOIN ed_visits v ON v.visit_date = s.d AND v.department = x.dept
GROUP BY s.d, x.dept ORDER BY s.d, x.dept;
| visit_date | department | |
|---|---|---|
| 2024-01-01 | Cardiology | 0 |
| 2024-01-01 | ER | 0 |
| 2024-01-02 | Cardiology | 0 |
| 2024-01-02 | ER | 2 |
| 2024-01-03 | Cardiology | 0 |
| 2024-01-03 | ER | 0 |
| 2024-01-04 | Cardiology | 1 |
| 2024-01-04 | ER | 0 |
| 2024-01-05 | Cardiology | 0 |
| 2024-01-05 | ER | 0 |
… 54 quiet rows omitted …
the 3 days with visits
| visit_date | department | |
|---|---|---|
| 2024-01-02 | ER | 2 |
| 2024-01-04 | Cardiology | 1 |
| 2024-01-07 | ER | 1 |
COUNT(v.visit_date), not COUNT(*) — after a LEFT JOIN, COUNT(*) counts the empty joined rows as 1 and your zeros become ones.v.department = x.dept) in the ON clause, not WHERE — WHERE filters after the join and kills your zero rows.CROSS JOIN multiplies: sanity-check the grid size (days × categories) before joining facts onto it.