[英]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.现在我需要获得相同的信息,但仅限于拥有超过 1 名患者的医生。 Please suggest me a query.请建议我查询。
Use HAVING
clause使用HAVING
子句
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.我使用别名( patients
)而不是COUNT(p.patientid)
,因为HAVING
子句允许这样做。 But you can stick to the COUNT(p.patientid)
as well但是您也可以坚持使用COUNT(p.patientid)
Also, I suggest you use all non-aggregated columns in the GROUP BY
clause.另外,我建议您在GROUP BY
子句中使用所有非聚合列。
And, if you retrieving doctorname
, you, probably, don't have to retrieve doctorid
.而且,如果您检索doctorname
,您可能不必检索doctorid
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.