sql >> Base de Datos >  >> RDS >> Mysql

MySQL Seleccione solo una fila de cada paciente diagnosticado según la primera fecha

Creo que lo que quiere es la primera visita y la última evaluación de diabetes. Supuse que el primer campo en todas sus tablas es un campo de incremento automático y que la consulta_id en el violín está escrita incorrectamente.

Dado lo anterior

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)