CREATE TABLE doctor( patient CHAR(13),docname CHAR(30) );
假设我有这样一张桌子,那么我如何显示患者最多的医生的名字?就像最多的是三个,两个医生有三个病人,然后我会显示他们的两个名字.
这将得到最大的患者:
SELECT MAX(count) FROM (SELECT COUNT(docname) FROM doctor GROUP BY docname) a;
这是所有的医生和他们有多少患者:
SELECT docname,COUNT(docname) FROM doctor GROUP BY name;
现在我无法弄清楚如何将它们结合起来只列出拥有最大患者的医生的名字.
谢谢.
解决方法
这应该做到这一点.
SELECT docname,COUNT(*) FROM doctor GROUP BY name HAVING COUNT(*) = (SELECT MAX(c) FROM (SELECT COUNT(patient) AS c FROM doctor GROUP BY docname))
另一方面,如果您只需要第一个条目,那么
SELECT docname,COUNT(docname) FROM doctor GROUP BY name ORDER BY COUNT(docname) DESC LIMIT 1;