|
| 1 | + |
| 2 | +# Total Doctor Visit Count by Facility |
| 3 | + |
| 4 | +> Count of completed doctor visit questionnaire responses grouped by facility for patients belonging to a given organization |
| 5 | +
|
| 6 | +## Purpose |
| 7 | + |
| 8 | +Counts completed responses to the doctor visit questionnaire (`questionnaire_id = 68`) per facility, scoped to living patients within a specified organization. |
| 9 | + |
| 10 | +## Parameters |
| 11 | + |
| 12 | +| Parameter | Type | Description | Example | |
| 13 | +|-----------|------|-------------|---------| |
| 14 | +| `organization_id` | TEXT | Organization external ID to scope patients (matched against `emr_organization.external_id`) | `'org-uuid-1234'` | |
| 15 | +| `date` | DATE / range | Metabase date filter (typically bound to `emr_questionnaireresponse.created_date`) | `'2026-07-01'` | |
| 16 | + |
| 17 | +--- |
| 18 | + |
| 19 | +## Query |
| 20 | + |
| 21 | +```sql |
| 22 | +WITH org_id AS ( |
| 23 | + SELECT emr_organization.id |
| 24 | + FROM emr_organization |
| 25 | + WHERE emr_organization.deleted = FALSE |
| 26 | + --AND emr_organization.external_id::text = {{organization_id}} |
| 27 | +), |
| 28 | +filtered_patients AS ( |
| 29 | + SELECT emr_patient.id |
| 30 | + FROM emr_patient |
| 31 | + INNER JOIN org_id ON TRUE |
| 32 | + WHERE emr_patient.deceased_datetime IS NULL |
| 33 | + AND emr_patient.organization_cache && ARRAY[org_id.id]::integer[] |
| 34 | +), |
| 35 | +visits AS ( |
| 36 | + SELECT |
| 37 | + emr_questionnaireresponse.id AS response_id, |
| 38 | + emr_questionnaireresponse.encounter_id |
| 39 | + FROM emr_questionnaireresponse |
| 40 | + INNER JOIN filtered_patients |
| 41 | + ON filtered_patients.id = emr_questionnaireresponse.patient_id |
| 42 | + WHERE emr_questionnaireresponse.questionnaire_id = 68 |
| 43 | + AND emr_questionnaireresponse.status = 'completed' |
| 44 | + AND emr_questionnaireresponse.encounter_id IS NOT NULL |
| 45 | + --[[AND {{date}}]] |
| 46 | +) |
| 47 | +SELECT |
| 48 | + facility_facility.name AS facility_name, |
| 49 | + COUNT(*) AS visit_count |
| 50 | +FROM visits |
| 51 | +INNER JOIN emr_encounter |
| 52 | + ON emr_encounter.id = visits.encounter_id |
| 53 | +INNER JOIN facility_facility |
| 54 | + ON facility_facility.id = emr_encounter.facility_id |
| 55 | + AND facility_facility.deleted = FALSE |
| 56 | +GROUP BY facility_facility.name |
| 57 | +ORDER BY visit_count DESC, facility_facility.name; |
| 58 | +``` |
| 59 | + |
| 60 | +## Notes |
| 61 | + |
| 62 | +- **Hardcoded IDs:** |
| 63 | + - `questionnaire_id = 68` — the doctor visit questionnaire at Karunashraya. Update if the questionnaire id changes. |
| 64 | +- **`organization_id` is required** (no `[[...]]` wrapper) — the query will not run without a value. |
| 65 | +- Results are ordered by visit count descending, then alphabetically by facility name for ties. |
| 66 | + |
| 67 | +*Last updated: 2026-07-15* |
0 commit comments