← Homepage

Date Spines and CROSS JOINs

October 11, 2026

Author: Daniel Jordan Viray

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.

Toy data

ed_visits — January has 31 days; only 3 of them have visits

visit_datedepartment
2024-01-02ER
2024-01-02ER
2024-01-04Cardiology
2024-01-07ER

The naive version — and what it hides

SELECT visit_date AS day, COUNT(*) AS visits
FROM ed_visits GROUP BY visit_date ORDER BY day;
dayvisits
2024-01-022
2024-01-041
2024-01-071

Three rows. The other 28 days of January simply don't exist here — any chart drawn from this is missing most of the month.

Step 1: build the spine (recursive CTE)

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.)

Step 2: CROSS JOIN the grid — every day × every department

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.

Step 3: LEFT JOIN the events onto the grid

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_datedepartment
2024-01-01Cardiology0
2024-01-01ER0
2024-01-02Cardiology0
2024-01-02ER2
2024-01-03Cardiology0
2024-01-03ER0
2024-01-04Cardiology1
2024-01-04ER0
2024-01-05Cardiology0
2024-01-05ER0

… 54 quiet rows omitted …

the 3 days with visits

visit_datedepartment
2024-01-02ER2
2024-01-04Cardiology1
2024-01-07ER1
Watch out.
Prove it. Every query on this page was run against SQLite and the tables show actual output — not hand-typed guesses.