001Level 1

Chapter 7 · CTEs

34. Hospital KPI Dashboard with Multiple CTEs

Hard40 XPHealthcare

Build a hospital-wide KPI report by department. For each department, compute: total doctors, total visits, total revenue, average bill per visit (rounded to 2 decimals), no-show rate (percentage of visits with status 'no_show', rounded to 1 decimal), and the name of the doctor with the most visits in that department (if tied, the alphabetically first name). Return all metrics in a single result set sorted by total revenue descending.

Tables

  • PKidINT
  • first_nameTEXT
  • last_nameTEXT
  • specialtyTEXT
  • FKdepartment_id→ departments.idINT
  • emailTEXT
  • phoneTEXT
  • hire_dateTEXT
  • salaryREAL
  • PKidINT
  • nameTEXT
  • floorINT
  • FKhead_doctor_id→ doctors.idINT
  • budgetREAL
  • PKidINT
  • FKpatient_id→ patients.idINT
  • FKdoctor_id→ doctors.idINT
  • visit_dateTEXT
  • diagnosisTEXT
  • notesTEXT
  • follow_up_dateTEXT
  • statusTEXT
  • PKidINT
  • FKvisit_id→ visits.idINT
  • amountREAL
  • insurance_coveredREAL
  • patient_responsibilityREAL
  • statusTEXT
  • billed_atTEXT
  • paid_atTEXT

Need help?

Ask Sol

AI tutor — looks at your current query and nudges you, without spoiling the answer.

Solution

Try the hints first — solving it yourself is what makes it stick.

Peek at the solution?

You can still earn the XP afterwards by submitting a working query — but you'll learn more if you give it one more try.