Applied Health Economics, RWE & HTA
Overview / Module 1 / Day 4
Module 1 · Health system & data · Day 4 of 100

Build the Warehouse with DuckDB and dbt

Days 1–3 worked on one year of claims read straight from CSV files. Real studies need many years, a registry that knows who died, and tables that every analyst on a project reads the same way. Today you rebuild the data as a warehouse: staging models that read the raw files, mart tables for people, claims, stays, drugs and person-years, and tests that run every time it is built. The tool is dbt (data build tool) on DuckDB. It is the same pattern analytics teams use in hospitals, consultancies and pharma RWE groups.

▶
Video for Day 4 coming soon

By the end of today you can

  • explain raw, staging and mart layers, and why each rule lives in one model
  • dbt build --profiles-dir . builds 23 models and passes 21 tests
  • explain survivor bias in a "current" registry
  • check row counts after every join, and every fact table has a unique test on its key
  • mart_annual_summary and the trend chart are built from the warehouse

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:35
4.1 Why a warehouse
0:35–1:15
4.2 Seven years of data, and the people the 2024 file missed
1:15–1:30
Break
1:30–2:20
4.3 A dbt project: staging and marts
2:20–3:00
4.4 Build and test
3:00–3:15
Break
3:15–3:45
4.5 A tour of the warehouse
3:45–4:05
4.6 A join that copies rows
4:05–4:45
4.7 Mini-project: seven years at a glance
4:45–5:00
4.8 Save your work
5:00–5:30
Bloc français

In this lesson

4.1 Why a warehouse (35 min)

On Day 3, every script repeated the same joins: claims to the fee table, drug claims to the drug table, stays to the province's cost per weighted case. That is fine for one person on one day. It breaks down when four analysts each write the join slightly differently, or when a new year of data arrives.

A warehouse puts each rule in one place:

LayerWhat it doesExample
RawThe files as delivered. Never editeddata/physician_claims_2023.csv.gz
Staging (stg_)One model per source: read it, set types, stack the years. No business rulesstg_physician_claims
Marts (dim_, fct_, mart_)Tables analysts use: one row per person, claim, stay or person-year, with the rules applied oncefct_hospital_stays (with cost), fct_person_years
TestsChecks that must pass every buildevery rx_id unique; every claim inside the person's registry window

dbt turns this into code. Each model is a SELECT statement in a .sql file. {{ ref('stg_drugs') }} points to another model, so dbt knows the build order. Tests are a few lines of YAML or SQL, and dbt build builds and tests everything in order. Because it is all text in Git, a reviewer can read exactly how cost was computed.

Why it matters at work: HTA reviewers and journal referees ask how each variable was derived. A dbt project answers with the code itself, plus tests showing the rules held.

Where you'll meet this: RWE teams in pharma and consulting · hospital analytics groups · any project with more than one analyst · Module 8's reproducible pipelines


4.2 Seven years of data, and the people the 2024 file missed (40 min)

Run the generator again. It keeps every Days 1–3 file byte for byte and adds:

  • claims for 2019–2023 and 2025, as gzipped CSV (*.csv.gz, which DuckDB reads directly)
  • registry_deceased_2019_2023.csv: people who died before 2024
  • registry_updates_2025.csv: deaths in 2025
  • drug_plan_eligibility_updates.csv: plan periods for those people, and people who turned 65 in 2025
  • Renavex's first claims, in Ontario from its listing on 1 October 2025
python data/make_data.py       # about 2.5 minutes; data/ grows to about 270 MB
"""Day 4.2: what the generator added, and why the 2024 file was not enough."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.db import DATA, show  # noqa: E402
import duckdb  # noqa: E402

con = duckdb.connect()
d = DATA.replace("\\", "/")

print("--- Claim files by year")
show(con, f"""
    SELECT year, physician, hospital, drug FROM (
        SELECT regexp_extract(filename, '(\\d{{4}})', 1)::INT AS year, 'physician' AS kind, count(*) AS n
        FROM read_csv('{d}/physician_claims_*.csv*', union_by_name = true, filename = true,
                      types = {{'fee_code': 'VARCHAR', 'dx_code': 'VARCHAR'}}) GROUP BY ALL
        UNION ALL
        SELECT regexp_extract(filename, '(\\d{{4}})', 1)::INT, 'hospital', count(*)
        FROM read_csv('{d}/hospital_discharges_*.csv*', union_by_name = true, filename = true,
                      types = {{'mrdx': 'VARCHAR', 'dx2': 'VARCHAR', 'dx3': 'VARCHAR', 'dx4': 'VARCHAR',
                                'cmg': 'VARCHAR', 'main_intervention': 'VARCHAR'}}) GROUP BY ALL
        UNION ALL
        SELECT regexp_extract(filename, '(\\d{{4}})', 1)::INT, 'drug', count(*)
        FROM read_csv('{d}/drug_claims_*.csv*', union_by_name = true, filename = true,
                      types = {{'din': 'VARCHAR'}}) GROUP BY ALL)
    PIVOT (sum(n) FOR kind IN ('physician', 'hospital', 'drug')) ORDER BY year""")

print("\n--- The registry, piece by piece")
show(con, f"""
    SELECT 'persons.csv (alive on 2024-01-01)' AS file, count(*) AS people, count(death_date) AS deaths
    FROM '{d}/persons.csv'
    UNION ALL
    SELECT 'registry_deceased_2019_2023.csv', count(*), count(death_date) FROM '{d}/registry_deceased_2019_2023.csv'
    UNION ALL
    SELECT 'registry_updates_2025.csv (deaths in 2025)', count(*), count(death_date)
    FROM '{d}/registry_updates_2025.csv'""")

print("\n--- Why the 2024 file alone misleads: deaths per 1,000 people alive on 1 January")
show(con, f"""
    WITH everyone AS (
        SELECT person_id, registry_start, death_date FROM '{d}/persons.csv'
        UNION ALL BY NAME
        SELECT person_id, registry_start, death_date FROM '{d}/registry_deceased_2019_2023.csv'),
    years AS (SELECT unnest(range(2019, 2025)) AS year)
    SELECT year,
           round(1000 * count_if(year(death_date) = year AND person_id LIKE 'P%')
                 / count_if(person_id LIKE 'P%'), 2)                                   AS using_2024_file_only,
           round(1000 * count_if(year(death_date) = year) / count(*), 2)              AS using_full_registry
    FROM everyone CROSS JOIN years
    WHERE registry_start <= make_date(year, 1, 1)
      AND (death_date IS NULL OR death_date >= make_date(year, 1, 1))
    GROUP BY year ORDER BY year""")
--- Claim files by year
 year  physician  hospital   drug
 2019     913844     25427 453469
 2020     925971     25662 510727
 2021     944419     25908 571086
 2022     970894     26389 642689
 2023    1008305     26912 735863
 2024    1058159     27619 823487
 2025    1065145     27206 762447

--- The registry, piece by piece
                                      file  people  deaths
         persons.csv (alive on 2024-01-01)  250000    2479
           registry_deceased_2019_2023.csv   12711   12711
registry_updates_2025.csv (deaths in 2025)    2495    2495

--- Why the 2024 file alone misleads: deaths per 1,000 people alive on 1 January
 year  using_2024_file_only  using_full_registry
 2019                  0.00                10.74
 2020                  0.00                10.34
 2021                  0.00                10.65
 2022                  0.00                10.98
 2023                  0.00                10.69
 2024                  9.94                 9.94

Look at the last table. persons.csv lists people alive on 1 January 2024. Measured with that file alone, nobody died in 2019–2023, because everyone who did is missing from it. This is survivor bias, and it creeps into real studies whenever someone takes "the current registry" as the population for earlier years. Any study that follows people from 2019 needs the full registry, deaths included. The warehouse builds that registry once, so nobody has to remember.


4.3 A dbt project: staging and marts (50 min)

The project lives in warehouse/:

warehouse/
├── dbt_project.yml        # project settings
├── profiles.yml           # where the DuckDB file lives
├── macros/                # read_data(), a generic test
├── models/
│   ├── staging/           # stg_*: one per source file
│   └── marts/             # dim_person, fct_*, mart_annual_summary, schema.yml (tests)
└── tests/                 # singular tests: one SQL query that must return no rows
name: corridor
version: "1.0.0"
config-version: 2
profile: corridor

model-paths: ["models"]
test-paths: ["tests"]
macro-paths: ["macros"]

vars:
  data_dir: "../data"      # relative to this folder: run dbt from warehouse/

models:
  corridor:
    staging:
      +materialized: table      # small: lookups, registry, eligibility
      stg_physician_claims:
        +materialized: ephemeral  # the big claim files are read straight into the marts
      stg_hospital_discharges:
        +materialized: ephemeral
      stg_drug_claims:
        +materialized: ephemeral
    marts:
      +materialized: table
corridor:
  target: dev
  outputs:
    dev:
      type: duckdb
      path: corridor.duckdb
      threads: 4

A small macro reads raw files with code columns kept as text (Day 3's lesson). The pattern physician_claims_*.csv* picks up the 2024 CSV and every .csv.gz year at once:

{# Read one CSV (or a glob of CSV and .csv.gz files) from data/, keeping code columns as text. #}
{% macro read_data(pattern, text_cols=[]) -%}
read_csv('{{ var("data_dir") }}/{{ pattern }}', union_by_name = true
         {%- if text_cols %}, types = { {%- for c in text_cols %}'{{ c }}': 'VARCHAR'{% if not loop.last %}, {% endif %}{% endfor -%} }{% endif %})
{%- endmacro %}

Staging. The registry model stacks the two registry files and applies the 2025 deaths. Claims models are one line each:

-- The registry: people alive on 2024-01-01, people who died in 2019-2023, and 2025 deaths.
with base as (
    select *, true as in_2024_file from {{ read_data('persons.csv') }}
    union all by name
    select *, false as in_2024_file from {{ read_data('registry_deceased_2019_2023.csv') }}
),
updates as (
    select person_id, death_date as death_date_2025 from {{ read_data('registry_updates_2025.csv') }}
)
select
    b.person_id, b.province, b.region, b.sex, b.birth_date, b.income_quintile, b.rural,
    b.registry_start,
    coalesce(b.death_date, u.death_date_2025) as death_date,
    b.in_2024_file
from base b
left join updates u using (person_id)
select * from {{ read_data('physician_claims_*.csv*', ['fee_code', 'dx_code']) }}

The three claim models are ephemeral: dbt pastes them into the marts as subqueries instead of creating views. A DuckDB view would store the relative path ../data/..., and that path only works when you run from warehouse/.

Marts. Each mart applies one rule. Hospital stays get their cost (Day 3), diagnoses are unpivoted (Day 3), and fct_person_years gives one row per person per year they were observed:

-- One row per discharge, costed as RIW x cost per weighted case (Day 3).
select
    h.abstract_id, h.person_id, h.province, h.admit_date, h.discharge_date, year(h.discharge_date) as discharge_year,
    h.los_days, h.mrdx, h.dx2, h.dx3, h.dx4, h.main_intervention, h.cmg, h.riw, h.discharge_disposition,
    round(h.riw * p.cost_per_weighted_case, 2) as cost
from {{ ref('stg_hospital_discharges') }} h
join {{ ref('stg_provinces') }} p using (province)
-- One row per person and calendar year they were observed (2019-2025):
-- observed days, death in the year, age on 1 January, and days on a public drug plan.
with years as (select unnest(range(2019, 2026)) as year),
spans as (
    select p.person_id, p.province, p.region, p.sex, p.birth_date, p.income_quintile, p.rural, y.year,
           greatest(p.registry_start, make_date(y.year, 1, 1))                        as obs_start,
           least(coalesce(p.death_date, make_date(y.year, 12, 31)), make_date(y.year, 12, 31)) as obs_end,
           p.death_date
    from {{ ref('dim_person') }} p cross join years y
),
observed as (
    select * from spans where obs_end >= obs_start
),
plan_days as (
    select o.person_id, o.year,
           sum(date_diff('day', greatest(o.obs_start, e.start_date),
                         least(o.obs_end, coalesce(e.end_date, o.obs_end))) + 1) as public_plan_days
    from observed o
    join {{ ref('stg_drug_plan_eligibility') }} e
      on e.person_id = o.person_id
     and e.start_date <= o.obs_end
     and coalesce(e.end_date, o.obs_end) >= o.obs_start
    group by all
)
select
    o.person_id, o.year, o.province, o.region, o.sex, o.income_quintile, o.rural,
    date_diff('year', o.birth_date, make_date(o.year, 1, 1))
        - (strftime(o.birth_date, '%m-%d') > '01-01')::int                  as age_jan1,
    o.obs_start, o.obs_end,
    date_diff('day', o.obs_start, o.obs_end) + 1                            as days_observed,
    coalesce(o.death_date between o.obs_start and o.obs_end, false)          as died,
    coalesce(pd.public_plan_days, 0)                                         as public_plan_days
from observed o
left join plan_days pd using (person_id, year)

fct_person_years is the denominator table for the rest of the course. It holds days observed, death in the year, age on 1 January, and days on a public drug plan (Day 2's coverage gap, now for every year).

Tests. schema.yml declares generic tests: unique, not_null, accepted_values, and relationships, which checks that every claim's person exists in dim_person:

version: 2

models:
  - name: dim_person
    description: One row per person in the registry, 2019-2025.
    columns:
      - name: person_id
        data_tests: [unique, not_null]
      - name: province
        data_tests:
          - accepted_values:
              arguments:
                values: ["ON", "QC"]
      - name: registry_start
        data_tests: [not_null]

  - name: fct_physician_claims
    columns:
      - name: claim_id
        data_tests: [unique, not_null]
      - name: person_id
        data_tests:
          - relationships:
              arguments:
                to: ref('dim_person')
                field: person_id
      - name: fee_description
        data_tests: [not_null]

  - name: fct_hospital_stays
    columns:
      - name: abstract_id
        data_tests: [unique, not_null]
      - name: person_id
        data_tests:
          - relationships:
              arguments:
                to: ref('dim_person')
                field: person_id
      - name: cost
        data_tests: [not_null]

  - name: fct_drug_dispensations
    columns:
      - name: rx_id
        data_tests: [unique, not_null]
      - name: person_id
        data_tests:
          - relationships:
              arguments:
                to: ref('dim_person')
                field: person_id
      - name: atc
        data_tests: [not_null]

  - name: fct_person_years
    data_tests:
      - unique_combination:
          arguments:
            columns: ["person_id", "year"]

A singular test is a query that must return no rows. Two catch rules that a type check cannot:

-- Every physician claim falls between the person's registry start and death.
select c.claim_id
from {{ ref('fct_physician_claims') }} c
join {{ ref('dim_person') }} p using (person_id)
where c.service_date < p.registry_start
   or c.service_date > coalesce(p.death_date, date '9999-12-31')
-- Every public drug claim falls inside one of the person's public plan periods, for that plan.
select r.rx_id
from {{ ref('fct_drug_dispensations') }} r
where not exists (
    select 1 from {{ ref('stg_drug_plan_eligibility') }} e
    where e.person_id = r.person_id and e.plan_id = r.plan_id
      and r.dispense_date >= e.start_date
      and r.dispense_date <= coalesce(e.end_date, date '9999-12-31')
)

4.4 Build and test (40 min)

From the warehouse folder:

cd warehouse
dbt build --profiles-dir .

dbt build runs every model and test in dependency order, and stops downstream models if a test fails. The course script calls dbt from Python and prints a summary without timings, so your output matches the notes:

"""Day 4.4: build the warehouse with dbt and list what was built and tested.

Same as running, from the warehouse folder:   dbt build --profiles-dir .
"""

import contextlib
import io
import os
import sys

from dbt.cli.main import dbtRunner

WAREHOUSE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "warehouse")
os.chdir(WAREHOUSE_DIR)

log = io.StringIO()
with contextlib.redirect_stdout(log):          # dbt's own log has timings; we print a stable summary
    result = dbtRunner().invoke(["build", "--profiles-dir", ".", "--quiet"])
if not result.success:
    print(log.getvalue())
    sys.exit("dbt build failed")

rows = []
for r in result.result:
    node = r.node
    kind = node.resource_type.value if hasattr(node.resource_type, "value") else str(node.resource_type)
    mat = node.config.materialized if kind == "model" else ""
    rows.append((kind, mat, node.name, str(r.status)))
order = {"model": 0, "test": 1}
rows.sort(key=lambda x: (order.get(x[0], 2), x[1], x[2]))
print(f"{'type':<7}{'materialized':<14}{'name':<72}status")
for kind, mat, name, status in rows:
    print(f"{kind:<7}{mat:<14}{name[:70]:<72}{status}")
print(f"\n{sum(k == 'model' for k, *_ in rows)} models, {sum(k == 'test' for k, *_ in rows)} tests, "
      f"{sum(s not in ('success', 'pass') for *_, s in rows)} problems")
type   materialized  name                                                                    status
model  table         dim_person                                                              success
model  table         fct_drug_dispensations                                                  success
model  table         fct_hospital_diagnoses                                                  success
model  table         fct_hospital_stays                                                      success
model  table         fct_person_years                                                        success
model  table         fct_physician_claims                                                    success
model  table         mart_annual_summary                                                     success
model  table         stg_atc                                                                 success
model  table         stg_cci                                                                 success
model  table         stg_cci_sections                                                        success
model  table         stg_cmg                                                                 success
model  table         stg_drug_plan_eligibility                                               success
model  table         stg_drug_plans                                                          success
model  table         stg_drugs                                                               success
model  table         stg_fee_codes                                                           success
model  table         stg_icd10                                                               success
model  table         stg_icd10_chapters                                                      success
model  table         stg_icd9_dx                                                             success
model  table         stg_persons                                                             success
model  table         stg_pharmacy_pricing                                                    success
model  table         stg_provinces                                                           success
model  table         stg_regions                                                             success
model  table         stg_renavex_milestones                                                  success
test                 accepted_values_dim_person_province__ON__QC                             pass
test                 claims_inside_registry_window                                           pass
test                 din_is_eight_characters                                                 pass
test                 drug_claims_on_a_public_plan                                            pass
test                 not_null_dim_person_person_id                                           pass
test                 not_null_dim_person_registry_start                                      pass
test                 not_null_fct_drug_dispensations_atc                                     pass
test                 not_null_fct_drug_dispensations_rx_id                                   pass
test                 not_null_fct_hospital_stays_abstract_id                                 pass
test                 not_null_fct_hospital_stays_cost                                        pass
test                 not_null_fct_physician_claims_claim_id                                  pass
test                 not_null_fct_physician_claims_fee_description                           pass
test                 relationships_fct_drug_dispensations_person_id__person_id__ref_dim_per  pass
test                 relationships_fct_hospital_stays_person_id__person_id__ref_dim_person_  pass
test                 relationships_fct_physician_claims_person_id__person_id__ref_dim_perso  pass
test                 stays_end_after_they_start                                              pass
test                 unique_combination_fct_person_years_person_id__year                     pass
test                 unique_dim_person_person_id                                             pass
test                 unique_fct_drug_dispensations_rx_id                                     pass
test                 unique_fct_hospital_stays_abstract_id                                   pass
test                 unique_fct_physician_claims_claim_id                                    pass

23 models, 21 tests, 0 problems

Python code now opens the warehouse read-only with corridor.db.warehouse():

def warehouse():
    """Read-only connection to the dbt-built warehouse (Day 4 onward)."""
    if not os.path.exists(WAREHOUSE):
        raise FileNotFoundError("warehouse/corridor.duckdb is missing: run  cd warehouse; dbt build --profiles-dir .")
    con = duckdb.connect(WAREHOUSE, read_only=True)
    con.execute("""CREATE TEMP MACRO age_on(birth, d) AS
                   date_diff('year', birth, d) - (strftime(d, '%m-%d') < strftime(birth, '%m-%d'))::INT""")
    return con

Try it (10 min). Write a singular test that fails if any hospital stay is discharged before it was admitted, or if los_days doesn't match the dates. Save it in warehouse/tests/ and rebuild.

Solution
-- Day 4 exercise: no hospital stay is discharged before it is admitted,
-- and the length of stay matches the dates.
select abstract_id
from {{ ref('fct_hospital_stays') }}
where discharge_date < admit_date
   or los_days <> date_diff('day', admit_date, discharge_date) + 1

It appears in the build summary above as stays_end_after_they_start ... pass. Tests like this cost nothing to keep, and they catch a broken data delivery before it reaches an analysis.


4.5 A tour of the warehouse (30 min)

"""Day 4.5: a tour of the warehouse."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.db import show, warehouse  # noqa: E402

con = warehouse()

print("--- Tables (marts) and their size")
show(con, """
    SELECT table_name, estimated_size AS rows
    FROM duckdb_tables() WHERE schema_name = 'main' ORDER BY table_name""")

print("\n--- One person's 2025 in the warehouse")
pid = con.sql("""SELECT person_id FROM fct_drug_dispensations WHERE din = '09900171'
                 ORDER BY person_id LIMIT 1""").fetchall()[0][0]
show(con, f"SELECT * FROM fct_person_years WHERE person_id = '{pid}' AND year >= 2023 ORDER BY year")
show(con, f"""SELECT dispense_date, ingredient, plan_id, total_cost, patient_paid, plan_paid
              FROM fct_drug_dispensations WHERE person_id = '{pid}' AND dispense_date >= DATE '2025-09-01'
              ORDER BY dispense_date, ingredient""")

print("\n--- Person-years by province and year")
show(con, """
    PIVOT (SELECT province, year, sum(days_observed) / 365.25 AS py FROM fct_person_years GROUP BY ALL)
    ON year USING round(sum(py))::BIGINT GROUP BY province ORDER BY province""")
--- Tables (marts) and their size
               table_name    rows
               dim_person  262711
   fct_drug_dispensations 4499768
   fct_hospital_diagnoses  323570
       fct_hospital_stays  185123
         fct_person_years 1717853
     fct_physician_claims 6886737
      mart_annual_summary      14
                  stg_atc      45
                  stg_cci       6
         stg_cci_sections       7
                  stg_cmg      13
stg_drug_plan_eligibility  118784
           stg_drug_plans       9
                stg_drugs      16
            stg_fee_codes      13
                stg_icd10      19
       stg_icd10_chapters       9
              stg_icd9_dx      12
              stg_persons  262711
     stg_pharmacy_pricing       2
            stg_provinces       2
              stg_regions      11
   stg_renavex_milestones       9

--- One person's 2025 in the warehouse
  person_id  year province region sex  income_quintile  rural  age_jan1  obs_start    obs_end  days_observed  died  public_plan_days
P00AB8A5E97  2024       ON ON-WST   F                5      0        99 2024-03-21 2024-12-31            286 False               286
P00AB8A5E97  2025       ON ON-WST   F                5      0       100 2025-01-01 2025-12-31            365 False               365
dispense_date              ingredient plan_id  total_cost  patient_paid  plan_paid
   2025-09-11           dapagliflozin  ODB-65       83.67          6.11      77.56
   2025-09-18                ramipril  ODB-65       12.23          6.11       6.12
   2025-10-10           dapagliflozin  ODB-65       83.67          6.11      77.56
   2025-10-19                ramipril  ODB-65       12.23          6.11       6.12
   2025-11-13           dapagliflozin  ODB-65       83.67          6.11      77.56
   2025-11-20                ramipril  ODB-65       12.23          6.11       6.12
   2025-11-23 renavexiban (fictional)  ODB-65      133.57          6.11     127.46
   2025-12-14           dapagliflozin  ODB-65       83.67          6.11      77.56
   2025-12-21                ramipril  ODB-65       12.23          6.11       6.12
   2025-12-27 renavexiban (fictional)  ODB-65      133.57          6.11     127.46

--- Person-years by province and year
province   2019   2020   2021   2022   2023   2024   2025
      ON 144572 147029 148774 151008 153132 154461 152707
      QC  88047  89657  90858  92159  93531  94450  93399

One person, three tables. In fct_person_years she joins the registry in March 2024, so 2024 has 286 observed days. In fct_drug_dispensations her autumn 2025 shows dapagliflozin and ramipril every month, and then, from 23 November, Renavex at $6.11 a fill to her and $127.46 to ODB. Those are Day 1's numbers, now part of a seven-year history.


4.6 A join that copies rows (20 min)

Bug of the day. A colleague wants each drug claim with the person's plan description, and joins claims to the eligibility table on person_id alone:

"""Day 4 bug of the day: a join that copies rows (fan-out).

A colleague wants each drug claim with the person's plan description, and joins the
claims to the eligibility table on person_id alone.
"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.db import warehouse  # noqa: E402

con = warehouse()
right = con.sql("""SELECT count(*), sum(plan_paid) FROM fct_drug_dispensations
                   WHERE dispense_year = 2025""").fetchall()[0]
wrong = con.sql("""
    SELECT count(*), sum(r.plan_paid), count(DISTINCT r.rx_id)
    FROM fct_drug_dispensations r
    JOIN stg_drug_plan_eligibility e ON e.person_id = r.person_id      -- the bug: no date or plan condition
    WHERE r.dispense_year = 2025""").fetchall()[0]
fixed = con.sql("""
    SELECT count(*), sum(r.plan_paid)
    FROM fct_drug_dispensations r
    JOIN stg_drug_plan_eligibility e
      ON e.person_id = r.person_id AND e.plan_id = r.plan_id
     AND r.dispense_date BETWEEN e.start_date AND coalesce(e.end_date, DATE '9999-12-31')
    WHERE r.dispense_year = 2025""").fetchall()[0]

print(f"2025 drug claims:            {right[0]:>9,}   plan paid ${right[1]:>14,.2f}")
print(f"after the person-only join:  {wrong[0]:>9,}   plan paid ${wrong[1]:>14,.2f}   "
      f"({wrong[2]:,} distinct claims)")
print(f"after joining on dates too:  {fixed[0]:>9,}   plan paid ${fixed[1]:>14,.2f}")
print(f"\nThe bug adds {wrong[0] - right[0]:,} copies and ${wrong[1] - right[1]:,.2f} of spending that never happened.")
print("dbt's unique test on rx_id would fail on the buggy model:",
      f"{wrong[0] - wrong[2]:,} duplicate rx_id rows.")
2025 drug claims:              762,447   plan paid $ 16,745,079.56
after the person-only join:    775,062   plan paid $ 17,046,244.38   (762,447 distinct claims)
after joining on dates too:    762,447   plan paid $ 16,745,079.56

The bug adds 12,615 copies and $301,164.82 of spending that never happened.
dbt's unique test on rx_id would fail on the buggy model: 12,615 duplicate rx_id rows.

People with two plan periods (social assistance before 65, then seniors' coverage) appear twice, once per period. That adds 12,615 claims and $301,164.82 of plan spending that never happened. The fix is to join on what makes the match unique: the plan and the date. The defence is a unique test on the key of every fact table. dbt would have failed the build before anyone saw the inflated cost.

Rule: after every join, check that the row count is what you expect. If one claim should match one plan period, the counts before and after must be equal.


4.7 Mini-project: seven years at a glance (40 min)

Build mart_annual_summary: one row per province and year, with person-years, deaths, physician claims, hospital stays and cost per person-year, people with two or more diabetes claims, SGLT2 users and Renavex users.

-- Day 4 mini-project: one row per province and year.
with py as (
    select province, year, count(*) as people_observed, sum(days_observed) / 365.25 as person_years,
           count_if(died) as deaths, sum(public_plan_days) / 365.25 as public_plan_years
    from {{ ref('fct_person_years') }} group by all
),
visits as (
    select province, service_year as year, count(*) as physician_claims, sum(paid_amount) as physician_paid
    from {{ ref('fct_physician_claims') }} group by all
),
diabetes as (
    -- two or more diabetes claims in the year: one-off rule-out visits barely move it
    select province, year, count(*) as people_2plus_diabetes_claims
    from (select person_id, any_value(province) as province, service_year as year
          from {{ ref('fct_physician_claims') }} where dx_code = '250'
          group by person_id, service_year having count(*) >= 2)
    group by all
),
stays as (
    select province, discharge_year as year, count(*) as stays, sum(cost) as hospital_cost
    from {{ ref('fct_hospital_stays') }} group by all
),
drugs as (
    select province, dispense_year as year, count(*) as drug_claims, sum(plan_paid) as drug_plan_paid,
           count(distinct person_id) filter (atc like 'A10BK%') as sglt2_users,
           count(distinct person_id) filter (din = '09900171') as renavex_users
    from {{ ref('fct_drug_dispensations') }} group by all
)
select
    province, year, people_observed, round(person_years) as person_years, deaths,
    round(1000 * deaths / person_years, 2)                 as deaths_per_1000_py,
    round(physician_claims / person_years, 2)              as claims_per_py,
    round(1000 * stays / person_years, 1)                  as stays_per_1000_py,
    round(hospital_cost / person_years, 2)                 as hospital_cost_per_py,
    round(public_plan_years)                               as public_plan_years,
    drug_claims, round(drug_plan_paid) as drug_plan_paid,
    people_2plus_diabetes_claims, sglt2_users, renavex_users
from py
left join visits using (province, year)
left join diabetes using (province, year)
left join stays using (province, year)
left join drugs using (province, year)
order by province, year
"""Day 4 mini-project: seven years at a glance, from the annual summary mart."""

import os
import sys

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.db import ROOT, show, warehouse  # noqa: E402

con = warehouse()
df = show(con, """SELECT province, year, people_observed, person_years, deaths_per_1000_py, claims_per_py,
                         stays_per_1000_py, hospital_cost_per_py, people_2plus_diabetes_claims, sglt2_users,
                         renavex_users
                  FROM mart_annual_summary ORDER BY province, year""")

fig, axes = plt.subplots(1, 3, figsize=(13, 3.6))
panels = [("people_2plus_diabetes_claims", "People with 2+ diabetes claims in the year"),
          ("sglt2_users", "SGLT2 inhibitor users (public plans)"),
          ("stays_per_1000_py", "Hospital stays per 1,000 person-years")]
for ax, (col, title) in zip(axes, panels):
    for prov, colour in (("ON", "#2563eb"), ("QC", "#d97706")):
        part = df[df.province == prov]
        ax.plot(part.year, part[col], marker="o", color=colour, label=prov)
    ax.set_title(title, fontsize=10)
    ax.set_xticks(range(2019, 2026))
    ax.tick_params(labelsize=8)
    ax.grid(alpha=0.3)
    ax.set_ylim(bottom=0)
axes[0].legend(frameon=False)
fig.tight_layout()
path = os.path.join(ROOT, "figures", "day04_trends.png")
fig.savefig(path, dpi=130, metadata={"Software": None})
print("\nSaved figures/day04_trends.png")
province  year  people_observed  person_years  deaths_per_1000_py  claims_per_py  stays_per_1000_py  hospital_cost_per_py  people_2plus_diabetes_claims  sglt2_users  renavex_users
      ON  2019           147214        144572               10.50           3.94              107.1                972.12                          9179         1324              0
      ON  2020           149360        147029               10.54           3.93              108.1                989.99                          9826         1491              0
      ON  2021           151506        148774               10.49           3.96              109.0                991.09                         10750         1722              0
      ON  2022           153830        151008               11.01           4.01              108.8                989.18                         11838         2144              0
      ON  2023           155942        153132               10.90           4.09              109.3                994.98                         13309         2931              0
      ON  2024           155122        154461                9.90           4.25              110.5               1001.61                         15116         3348              0
      ON  2025           153593        152707               10.27           4.33              110.9                994.62                         16812         3647            724
      QC  2019            89686         88047               10.95           3.91              109.0                929.90                          5391          840              0
      QC  2020            91125         89657                9.76           3.88              109.2                929.99                          5777          967              0
      QC  2021            92547         90858               10.72           3.92              106.6                906.08                          6424         1142              0
      QC  2022            93846         92159               10.73           3.96              107.6                927.89                          7093         1380              0
      QC  2023            95276         93531               10.16           4.09              108.9                938.72                          8024         1902              0
      QC  2024            94878         94450               10.06           4.25              111.7                960.95                          9205         2212              0
      QC  2025            93928         93399                9.91           4.33              109.9                950.90                         10283         2367              0

Saved figures/day04_trends.png

Trends 2019-2025 by province

What to notice:

  • Hospital use is flat at about 110 stays per 1,000 person-years, and hospital cost per person-year stays close to $1,000 in Ontario and $950 in Quebec.
  • Diabetes and SGLT2 use climb every year. Corridor Health has many recent diabetes diagnoses, a steeper rise than in real Canadian data. It makes incidence questions (Day 5) have enough cases.
  • Renavex appears in Ontario only, with 724 users in its first three months. Quebec lists it in February 2026, after the end of the data.
  • Why "2+ claims in the year"? Plain "any diabetes claim" counts one-off rule-out visits too, which makes it noisy. Day 5 measures exactly how noisy.

4.8 Save your work (15 min)

The DuckDB file, dbt's target/ and logs/ folders, and the generated data are all rebuilt from code, so .gitignore keeps them out:

.venv/
__pycache__/
.pytest_cache/
*.duckdb
*.duckdb.wal
warehouse/target/
warehouse/logs/
warehouse/.user.yml
logs/
figures/*.png
# generated data: rebuild with python data/make_data.py
data/*.csv
data/*.csv.gz
data/truth/
python -m pytest -q
git add .
git commit -m "Day 4: dbt warehouse, 2019-2025"

Day 4 checklist

  • I can explain raw, staging and mart layers, and why each rule lives in one model
  • dbt build --profiles-dir . builds 23 models and passes 21 tests
  • I can explain survivor bias in a "current" registry
  • I check row counts after every join, and every fact table has a unique test on its key
  • mart_annual_summary and the trend chart are built from the warehouse