Given a highly normalized database schema, write a SQL query to extract a specific set of patient metrics, utilizing window functions.
Use the normalized patient, facility, and encounter data. Include all patients and calculate metrics for encounters beginning in calendar year 2025.
Output
- One row per patient, including patients with no qualifying encounters.
- Columns:
patient_id, patient_name, facility_id, encounter_count, average_length_hours, latest_encounter_date, and facility_encounter_rank.
- Rank patients within each facility by encounter count descending, with ties sharing a rank.
- Order by facility, rank, and patient ID, placing patients without a facility last.