Mysql
 sql >> Database >  >> RDS >> Mysql

MySQL Selezionare solo una riga per ogni paziente diagnosticato in base alla prima data

Penso che quello che vuoi sia la prima visita e l'ultima valutazione del diabete. Ho presupposto che il primo campo in tutte le tue tabelle sia un campo auto_increment e che consulting_id nel violino sia digitato in modo errato.

Dato quanto sopra

MariaDB [sandbox]> select p.patient_name_en,v.*,c.diagnosis_id,d.diagnosis_name,da.date_of_assessment,da.assessment_result
    -> from visit v
    -> join patient p on p.patient_id = v.patient_id
    -> join consultation c on c.patient_id = v.patient_id and c.visit_id = v.visit_id
    -> join diagnosis d on d.diagnosis_id = c.diagnosis_id
    -> left join
    -> (
    -> select da.patient_id, da.date_of_assessment,da.assessment_result
    -> from diabetes_assessment da
    -> where da.diabetes_assessment_id  = (select max(da1.diabetes_assessment_id) from diabetes_assessment da1 where da1.patient_id = da.patient_id)
    -> ) da on da.patient_id = v.patient_id
    -> where v.visit_id = (select min(visit_id) from consultation c where c.patient_id = v.patient_id)
    -> and c.diagnosis_id in (1,2)
    -> and v.clinic_id = 361
    -> ;
+-----------------+----------+------------+-----------+---------------+--------------+--------------+---------------------------------------------+--------------------+-------------------+
| patient_name_en | visit_id | patient_id | clinic_id | date_of_visit | visit_status | diagnosis_id | diagnosis_name                              | date_of_assessment | assessment_result |
+-----------------+----------+------------+-----------+---------------+--------------+--------------+---------------------------------------------+--------------------+-------------------+
| ABC             |        1 | 361-9001   |       361 | 2017-03-03    | Active       |            1 | Diabetes mellitus with diabetic nephropathy | 2017-05-05         |             40.00 |
| XYZ             |        3 | 361-0361   |       361 | 2017-10-03    | Active       |            2 | E01 Diabetes mellitus with kidney disease   | 2017-03-10         |             30.50 |
+-----------------+----------+------------+-----------+---------------+--------------+--------------+---------------------------------------------+--------------------+-------------------+
2 rows in set (0.00 sec)