Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

MySQL Selecione apenas uma linha de cada paciente diagnosticado de acordo com a primeira data


Acho que o que você quer é a primeira consulta e a última avaliação do diabetes. Eu assumi que o primeiro campo em todas as suas tabelas é um campo auto_increment e que consultation_id no violino está digitado incorretamente.

Dado o acima
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)