Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select from inner join where count greater than

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.

like image 340
Dilukshan Mahendra Avatar asked Mar 02 '14 13:03

Dilukshan Mahendra


1 Answers

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.

like image 175
Alexander Avatar answered Nov 10 '22 11:11

Alexander