IntermediateSubqueries25 points

Departments that keep patients longer than the hospital average

The quality committee wants to find departments whose patients stay longer than the typical patient across the whole network. A stay is the number of days between admit_date and discharge_date; admissions without a discharge date are ignored everywhere in this task, including in the network average.

Task: return department (name), avg_stay_days (the department average, ROUND(x, 2)), hospital_avg_days (the average over all discharged admissions, ROUND(x, 2)) and extra_days (department average minus hospital average computed from the unrounded values, then ROUND(x, 2)). Keep only departments above the hospital average. Sort by extra_days from high to low, then by department A to Z.

The data you can query

Each table is shown with its column types and the first rows, so you can see exactly what the data looks like.

admissions99 rows
admission_id INTEGERpatient_id INTEGERdoctor_id INTEGERdept_id INTEGERadmit_date TEXTdischarge_date TEXTdiagnosis TEXTtotal_cost_usd INTEGER
1391422024-08-032024-08-11Tumor resection15320
211662024-08-122024-08-15Poisoning4480
352552024-09-172024-09-28Dehydration12560
4251152024-09-182024-09-27Asthma attack9390
551152024-09-202024-09-29Dehydration12860
6221312024-10-162024-10-28Chest pain18330

Showing the first 6 of 99 rows.

departments6 rows
dept_id INTEGERname TEXThospital TEXT
1CardiologyMeridian Central Hospital
2OncologyMeridian Central Hospital
3OrthopedicsLakeshore Medical Center
4NeurologyMeridian Central Hospital
5PediatricsLakeshore Medical Center
6Emergency MedicineLakeshore Medical Center
doctors15 rows
doctor_id INTEGERname TEXTdept_id INTEGERcountry TEXT
1Dr. Jakub Zielinski1Poland
2Dr. Lucia Romero2Spain
3Dr. Tunde Adeyemi3Nigeria
4Dr. Rohan Nair4India
5Dr. Elena Vidal5Spain
6Dr. Thiago Pereira6Brazil

Showing the first 6 of 15 rows.

lab_results110 rows
lab_id INTEGERadmission_id INTEGERpatient_id INTEGERtest_name TEXTunit TEXTlab_date TEXTresult_value REALref_low REALref_high REAL
1139HbA1c%2024-08-048.4345.7
2211Creatininemg/dL2024-08-121.040.61.3
3352LDL Cholesterolmg/dL2024-09-18149.2950130
4425LDL Cholesterolmg/dL2024-09-1892.0850130
555Creatininemg/dL2024-09-211.660.61.3
6622LDL Cholesterolmg/dL2024-10-16172.1550130

Showing the first 6 of 110 rows.

patients60 rows
patient_id INTEGERname TEXTgender TEXTbirth_date TEXTcountry TEXT
1Ethan ReedF1995-04-12United States
2Hanna NowakF1972-04-23Poland
3Karim SalemM1976-06-17Egypt
4Jules GirardF1993-09-05France
5Hannah HartmannF2017-04-08Germany
6Lucia NavarroF1974-06-27Spain

Showing the first 6 of 60 rows.

Your query runs on SQLite. Write a single SELECT; use LIMIT instead of TOP.

Need a hint?

A scalar subquery in HAVING can hold the network-wide average.