Doctor
doctorid (PK) doctorname
Patient
patientid (PK) patientname doctorid
I have the following query to get the doctors details with the number of patients that he/she consults. assume a patient has only one doctor to consult.
select d.doctorid,d.doctorname,count(p.patientid) from doctor d inner join patient p on d.doctorid = p.doctorid group by p.doctorid
Now I need to get the same information but only for the doctors who has more than 1 patients. Please suggest me a query.
Advertisement
Answer
Use HAVING
clause
SELECT d.doctorid, d.doctorname, COUNT(p.patientid) AS patients FROM doctor d INNER JOIN patient p ON d.doctorid = p.doctorid GROUP BY d.doctorid, d.doctorname HAVING patients > 1
I used alias (patients
) instead of COUNT(p.patientid)
, because HAVING
clause allows that. But you can stick to the COUNT(p.patientid)
as well
Also, I suggest you use all non-aggregated columns in the GROUP BY
clause.
And, if you retrieving doctorname
, you, probably, don’t have to retrieve doctorid
.