|
| 1 | +/* |
| 2 | +Question 3586. Find COVID Recovery Patients |
| 3 | +Link: https://leetcode.com/problems/find-covid-recovery-patients/description/?envType=problem-list-v2&envId=database |
| 4 | +
|
| 5 | +Table: patients |
| 6 | +
|
| 7 | ++-------------+---------+ |
| 8 | +| Column Name | Type | |
| 9 | ++-------------+---------+ |
| 10 | +| patient_id | int | |
| 11 | +| patient_name| varchar | |
| 12 | +| age | int | |
| 13 | ++-------------+---------+ |
| 14 | +patient_id is the unique identifier for this table. |
| 15 | +Each row contains information about a patient. |
| 16 | +Table: covid_tests |
| 17 | +
|
| 18 | ++-------------+---------+ |
| 19 | +| Column Name | Type | |
| 20 | ++-------------+---------+ |
| 21 | +| test_id | int | |
| 22 | +| patient_id | int | |
| 23 | +| test_date | date | |
| 24 | +| result | varchar | |
| 25 | ++-------------+---------+ |
| 26 | +test_id is the unique identifier for this table. |
| 27 | +Each row represents a COVID test result. The result can be Positive, Negative, or Inconclusive. |
| 28 | +Write a solution to find patients who have recovered from COVID - patients who tested positive but later tested negative. |
| 29 | +
|
| 30 | +A patient is considered recovered if they have at least one Positive test followed by at least one Negative test on a later date |
| 31 | +Calculate the recovery time in days as the difference between the first positive test and the first negative test after that positive test |
| 32 | +Only include patients who have both positive and negative test results |
| 33 | +Return the result table ordered by recovery_time in ascending order, then by patient_name in ascending order. |
| 34 | +*/ |
| 35 | + |
| 36 | +WITH first_positive AS ( |
| 37 | + SELECT |
| 38 | + patient_id, |
| 39 | + MIN(test_date) AS positive |
| 40 | + FROM covid_tests |
| 41 | + WHERE result = 'Positive' |
| 42 | + GROUP BY patient_id |
| 43 | +), |
| 44 | + |
| 45 | +first_negative AS ( |
| 46 | + SELECT |
| 47 | + ct.patient_id, |
| 48 | + MIN(ct.test_date) AS negative, |
| 49 | + MIN(fp.positive) AS positive |
| 50 | + FROM covid_tests AS ct |
| 51 | + LEFT JOIN |
| 52 | + first_positive AS fp |
| 53 | + ON ct.patient_id = fp.patient_id |
| 54 | + WHERE ct.result = 'Negative' AND ct.test_date > fp.positive |
| 55 | + GROUP BY ct.patient_id |
| 56 | +) |
| 57 | + |
| 58 | +SELECT |
| 59 | + fn.patient_id, |
| 60 | + p.patient_name, |
| 61 | + p.age, |
| 62 | + fn.negative - fn.positive AS recovery_time |
| 63 | +FROM first_negative AS fn |
| 64 | +LEFT JOIN |
| 65 | + patients AS p |
| 66 | + ON fn.patient_id = p.patient_id |
| 67 | +ORDER BY recovery_time ASC, p.patient_name ASC |
0 commit comments