Interview Question Bank · COUNT(DISTINCT) · HAVING · date range
4. Patients seen by 3+ doctors
MediumHealthcareQuestion #136
Concept: COUNT(DISTINCT) · HAVING · date rangeshow
To count different things, not rows, use COUNT(DISTINCT col): five visits with two people is 2. HAVING then keeps only groups that pass a threshold. Apply the row-level rules (which statuses count, which dates) in WHERE first, so they shape both counts.
Example (different data):
SELECT customer_id, COUNT(DISTINCT store_id) AS stores FROM purchases WHERE status = 'completed' AND bought_on BETWEEN '2025-01-01' AND '2025-03-31' GROUP BY customer_id HAVING COUNT(DISTINCT store_id) >= 3;
Your task
Larkspur Health's care-coordination team wants to find patients whose care is spread across many doctors in the first half of 2025, to offer them a single care coordinator. Only appointments that actually happened count.
Using completed appointments dated 2025-01-01 through 2025-06-30 (both included), return name, doctors_seen (distinct doctors) and completed_visits for patients who saw at least 3 different doctors. Sort by doctors_seen descending, then name.
Starting Postgres in your browser…
Checking your access…