{"id":45635583,"url":"https://github.com/space-lumps/healthcare-analytics-sql","last_synced_at":"2026-03-03T04:25:42.310Z","repository":{"id":336346556,"uuid":"1149249311","full_name":"space-lumps/healthcare-analytics-sql","owner":"space-lumps","description":"Healthcare analytics SQL project focused on defining clean encounter-level cohorts, deriving patient and visit features, and validating data quality through explicit QA checks. The repository emphasizes reproducible, well-structured SQL, clear cohort logic, and diagnostic queries suitable for real-world healthcare or clinical analytics workflows.","archived":false,"fork":false,"pushed_at":"2026-02-16T06:18:31.000Z","size":106,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-02-24T06:27:00.373Z","etag":null,"topics":["analytics-engineering","cohort-analysis","csv","csv-processing","data-modeling","data-quality","data-validation","duckdb","etl","healthcare-analytics","normalization","qa-validation","sql"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/space-lumps.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-02-03T22:32:21.000Z","updated_at":"2026-02-16T06:18:35.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/space-lumps/healthcare-analytics-sql","commit_stats":null,"previous_names":["space-lumps/healthcare-analytics-sql"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/space-lumps/healthcare-analytics-sql","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/space-lumps%2Fhealthcare-analytics-sql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/space-lumps%2Fhealthcare-analytics-sql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/space-lumps%2Fhealthcare-analytics-sql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/space-lumps%2Fhealthcare-analytics-sql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/space-lumps","download_url":"https://codeload.github.com/space-lumps/healthcare-analytics-sql/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/space-lumps%2Fhealthcare-analytics-sql/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30031982,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-03T03:27:35.548Z","status":"ssl_error","status_checked_at":"2026-03-03T03:27:09.213Z","response_time":61,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["analytics-engineering","cohort-analysis","csv","csv-processing","data-modeling","data-quality","data-validation","duckdb","etl","healthcare-analytics","normalization","qa-validation","sql"],"created_at":"2026-02-24T01:47:30.189Z","updated_at":"2026-03-03T04:25:42.305Z","avatar_url":"https://github.com/space-lumps.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Healthcare Analytics - Clinical Cohort Construction in SQL\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![CI - Smoke](https://github.com/space-lumps/healthcare-analytics-sql/actions/workflows/sql-pipeline-smoke.yml/badge.svg)](https://github.com/space-lumps/healthcare-analytics-sql/actions/workflows/sql-pipeline-smoke.yml)\n[![CI - Validation](https://github.com/space-lumps/healthcare-analytics-sql/actions/workflows/sql-pipeline-validation.yml/badge.svg)](https://github.com/space-lumps/healthcare-analytics-sql/actions/workflows/sql-pipeline-validation.yml)\n[![DuckDB](https://img.shields.io/badge/DuckDB-1.1+-yellow?logo=duckdb\u0026logoColor=white)](https://duckdb.org/)\n[![Latest Release](https://img.shields.io/github/v/release/space-lumps/healthcare-analytics-sql?color=brightgreen\u0026logo=github)](https://github.com/space-lumps/healthcare-analytics-sql/releases/latest)\n\n## Table of Contents\n\n- [Overview](#overview)\n- [Objective](#objective)\n- [Cohort Definition](#cohort-definition)\n- [Metrics \u0026 Features Produced](#metrics--features-produced)\n- [Validation \u0026 QA](#validation--qa)\n- [Continuous Integration](#continuous-integration)\n- [Repository Structure](#repository-structure)\n- [How to Run](#how-to-run)\n- [Data](#data)\n- [Design Philosophy](#design-philosophy)\n- [Key Takeaways \u0026 Lessons Learned](#key-takeaways--lessons-learned)\n- [License](#license)\n\n---\n\n### Overview\n\nThis repository implements a **reproducible analytics-engineering workflow** for healthcare encounter data using SQL. The project focuses on constructing a clinically meaningful cohort, deriving encounter-level metrics, and validating results with explicit QA tests.\n\nThe end result is an **analysis-ready cohort table** at a clear grain (`patient_id + encounter_id`) that can be safely used downstream for reporting, modeling, or further analysis.\n\n---\n\n### Objective\n\n* Define a drug overdose hospital encounter cohort using explicit clinical and demographic criteria\n* Engineer encounter-level features commonly used in healthcare analytics\n* Validate complex logic (e.g., readmissions, age calculation) with standalone test queries\n* Demonstrate production-style SQL organization, normalization, and quality checks\n\n---\n\n### Cohort Definition\n\nThe cohort includes hospital encounters that meet all of the following:\n\n* `encounters.encounter_reason = 'Drug overdose'`\n* Encounter start date after **1999-07-15**\n* Patient age at encounter between **18 and 35** (inclusive, birthday-accurate calculation)\n\nThe cohort is built as a **TEMP VIEW** to support iterative analysis and validation.\n\n---\n\n### Metrics \u0026 Features Produced\n\nEach row represents **one patient encounter** and includes:\n\n* `death_at_visit_ind`  \n  Indicator for death occurring during the encounter window\n\n* `count_current_meds`  \n  Count of medications active at encounter start\n\n* `current_opioid_ind`  \n  Indicator for active opioid medications at encounter start\n\n* `readmission_90_day_ind`  \n  Indicator for overdose readmission within 90 days\n\n* `readmission_30_day_ind`  \n  Indicator for overdose readmission within 30 days\n\n* `first_readmission_date`  \n  Date of first qualifying readmission, if any\n\nAll metrics are derived explicitly in SQL with documented assumptions and tested constraints.\n\n---\n\n### Validation \u0026 QA\n\nThe repo includes **dedicated validation queries** to verify correctness of key logic, including:\n\n* Independent recalculation of readmission indicators  \n* Comparison of age calculation methods (year-diff vs birthday-accurate)  \n* Validation that readmission counts are unaffected by cohort-side age filtering  \n* Duplicate grain checks (`patient_id + encounter_id`)  \n* Source reconciliation and join fanout checks  \n* Null and range validation tests  \n\nKey validated findings include:\n\n* `encounters.id` is unique (no encounter-level deduplication required)\n* `encounters.stop` contains no null values (validated during QA)\n* Expanding readmission logic beyond the age-filtered cohort produced identical results in the production and sample datasets\n* Medication deduplication was required and handled during normalization\n\nValidation logic lives alongside the pipeline and can be run independently.\nValidation summary is documented in `docs/validation_summar.md`\n* Tests with the `recon` prefix independently recompute cohort-selection logic before downstream schema and metric validation.\n\n---\n\n### Continuous Integration\n\nThis repository uses **GitHub Actions** to automatically validate the SQL pipeline on pushes to `main` or `refactor/*` branches, and on pull requests targeting `main`. Two complementary workflows provide layered protection: quick syntax/output checks for speed, and deeper data quality validation for confidence.\n\nTwo complementary workflows are defined in `.github/workflows/`:\n\n#### 1. Smoke Pipeline Checks (`sql-pipeline-smoke.yml`)\n\nThis lightweight workflow runs on every relevant push and pull request, and serves as a fast \"does it still build and produce output?\" gate.\n\n- **Build \u0026 Schema Check** — Executes the full pipeline (normalization → cohort building → feature derivation) in a clean DuckDB environment and verifies that:\n  - All SQL scripts parse without syntax errors\n  - Expected tables/views are created with the correct schema (column names, types, grain)\n\n- **Validate Output CSV** — Confirms that the final output CSV is generated successfully and contains the expected columns/structure (basic row count and header validation).\n\nPurpose: Detect breaking changes quickly so feedback arrives early in development or review cycles.\n\n#### 2. Full Validation Pipeline (`sql-pipeline-validation.yml`)\n\nThis more comprehensive workflow is also triggered by the same events (and can be manually dispatched if needed). It focuses on deep data quality assurance.\n\n- **Data Quality Checks** — Executes nearly all SQL test queries located in `sql/pipeline/tests/` **in serial** (one after another) against the pipeline output.  \n  - Executes the automated data quality tests from `sql/pipeline/tests/` against the pipeline output  \n  (includes grain/consistency checks, source-to-derived reconciliation, null \u0026 duplicate scans, and key business logic validations such as readmission flags and age calculations)\n  - Excludes `40_final_sanity.sql`, which remains reserved for manual / ad-hoc review\n\n**Purpose:** Ensures core analytics logic, feature derivations, and data invariants stay correct through refactors, logic updates, or schema changes.\n\nTogether, these workflows enforce deterministic, testable SQL practices and help deliver production-grade reliability in an open-source healthcare analytics project.\n\n---\n\n### Repository Structure\n\n```text\n.\n├─ sql/\n│  ├─ explore/\n│  │  ├─ 01_source_files_exploration.sql\n│  │  └─ 02_source_files_exploration_NA.sql\n│  └─ pipeline/\n│     ├─ 10_normalize_sources.sql\n│     ├─ 20_build_cohort.sql\n│     ├─ 30_output_csv.sql\n│     └─ tests/\n│        ├─ 00_recon_expected.sql\n│        ├─ 01_recon_unexpected.sql\n│        ├─ 02_recon_counts.sql\n│        ├─ 03_recon_fanout.sql\n│        ├─ 10_schema.sql\n│        ├─ 11_grain.sql\n│        ├─ 20_cohort_criteria.sql\n│        ├─ 30_metric_logic.sql\n│        ├─ 31_nulls_ranges.sql\n│        └─ 40_final_sanity.sql\n│\n├─ datasets/\n│  ├─ prod/       (gitignored)\n│  └─ sample/\n│     ├─ encounters.csv\n│     ├─ medications.csv\n│     └─ patients.csv\n│\n├─ docs/\n│  ├─ assumptions.md\n│  ├─ run_instructions.md\n│  ├─ validation_summary.md\n│  └─ data-dictionary-csvs/\n│\n├─ output/        (gitignored)\n│\n└─ README.md\n```\n\n---\n\n### How to Run\n\n* SQL engine: **DuckDB**\n* DuckDB must be started from `sql/pipeline/` for relative paths to resolve correctly\n* Scripts are numbered and must be executed in order\n* `10_normalize_sources.sql` must be executed before `20_build_cohort.sql`, followed by `30_output_csv.sql`\n* Validation tests can be run after the cohort TEMP VIEW is created\n\nDetailed environment setup and execution instructions are documented in `docs/run_instructions.md`.\n\n\n---\n### Data\n\nRaw source files are not committed to this repository. The project separates local production inputs from reproducible sample data:\n\n- `datasets/prod/`  \n  Local, production-scale source files (gitignored).\n\n- `datasets/sample/`  \n  Synthetic sample CSVs included to make the pipeline runnable and to exercise key edge cases.\n\nNotes:\n- Raw encounter timestamps are stored as UTC in the source data and preserved as TIMESTAMP during normalization to maintain full temporal precision.\n- The pipeline operates on normalized DuckDB TEMP VIEWs generated by `10_normalize_sources.sql`.\n- Tested constraints, assumptions, and validation findings are documented in `/docs`.\n- Switch between `datasets/sample/` and `datasets/prod/` by updating the `dataset_root()` macro at the top of `10_normalize_sources.sql`.\n\n---\n\n### Design Philosophy\n\nThis project follows analytics engineering best practices:\n\n* Explicit grain definition  \n* Deterministic business logic  \n* Separation of normalization and feature engineering  \n* Independent QA validation  \n* Documented assumptions and tested constraints  \n\nThese principles ensure the pipeline is reproducible, auditable, and production-like, mirroring workflows in healthcare and clinical data teams.\n\n### Key Takeaways \u0026 Lessons Learned\n\n- **Dedicated QA/validation is non-negotiable** — Writing standalone test queries for critical logic (age calculation, readmission flags, grain integrity) catches subtle bugs that simple counts miss and builds confidence for downstream use.\n- **Modular, numbered SQL files enhance debuggability** — Sequencing scripts (10_normalize → 20_cohort → 30_output + tests/) allows independent execution, easier troubleshooting, and clearer collaboration compared to monolithic queries.\n- **DuckDB excels for local prototyping** — Running full pipelines on sample data with near-production SQL syntax enables rapid iteration without spinning up a database server or dealing with connection overhead.\n- **Transparent documentation of assumptions prevents misinterpretation** — Maintaining a separate assumptions.md file (plus inline comments) clarifies scope, edge cases, and design decisions for reviewers or future self.\n- **Cohort logic is the foundation** — Investing upfront in precise, reproducible cohort definition avoids propagating errors through feature derivation and metrics.\n\n---\n\n### License\n\nMIT License  \nCopyright (c) 2026 Corin Stedman  \n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspace-lumps%2Fhealthcare-analytics-sql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspace-lumps%2Fhealthcare-analytics-sql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspace-lumps%2Fhealthcare-analytics-sql/lists"}