I have a patient
table and a reference
table as below
patient
table
id name
1 Doni
2 Doni
3 Doni
4 Tejo
5 Bambang
reference
table
patient_id refer_to_patient_id
1 2
2 3
3 null
refer_to_patient_id null means patient name Doni is referred to another Hospital but the Hospital it's referred to has not created a record.
And I need to count how many patient they have. Example above should return 3 patients as record id 1,2,3 is the same patient. Patient name could be different even for the same patient since they are inputted from different hospitals.
PS: patient table is actually not patient entity, it's a medical record (EMR) and a hospital can refer a patient (or an EMR) to another hospital and it is counted as a single patient.
While initially it seems like you need to resolve the full tree, I think that the question you're asking is as simple as
select
count(distinct pat.id) patients
from
patient pat
left outer join reference ref on pat.id = ref.patient_id
where
ref.patient_id is null;
That is, an id
should only be counted when it does not have a map to another id
. Put another way, any id
value that does not have a mapped value is the end of the hierarchy.
MySQL has a DISTINCT
keyword.
SELECT count(DISTINCT name)
FROM patient;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.