Patient(patientId, name, gender, DoB, address, state,postcode, homePhone, businessPhone, maritalStatus, occupation, duration,unit, race, registrationDate , GPNo, NaturopathNo)
和
Naturopath (NaturopathNo, name, contactNo, officeStartTime, officeEndTime, emailAddress)
现在查询这个我想出来了
SELECT count(*), naturopathno FROM dbf10.patient WHERE naturopathno != 'NULL' GROUP BY naturopathno;
导致;
COUNT(*) NATUROPATH
2 NP5
1 NP6
3 NP2
1 NP1
2 NP3
1 NP7
2 NP8
我的问题是,如何从此列表中选择最高计数,并使用自然疗法名称打印该值?任何建议都非常欢迎,
答案 0 :(得分:2)
在MySQL中,您可以选择顶行,如:
select *
from Naturopath n
join (
SELECT count(*) as cnt, naturopathno
FROM dbf10.patient
WHERE naturopathno != 'NULL'
GROUP BY naturopathno;
) pat ON pat.naturopathno = n.naturopathno
ORDER BY pat.cnt DESC
LIMIT 1
顺便说一下,如果您要检查null
而不是字符串"NULL"
,请尝试:
where naturopathno is not null
答案 1 :(得分:1)
您可以使用RANK分析函数 - 这将为最顶层的自然疗法分配等级“1”,如果第一个地方有一个平局,则为自然疗法:
SELECT (select name from Naturopath n
where n.NaturopathNo = q.naturopathno)
as TopNaturopathName,
,q.patients
FROM (
SELECT naturopathno, patients,
RANK() OVER (ORDER BY patients DESC) rnk
FROM (
SELECT COUNT(*) AS patients, naturopathno
FROM dbf10.patient
WHERE naturopathno is not null
GROUP BY naturopathno
)
) q
WHERE rnk = 1;
答案 2 :(得分:0)
好吧想通了,谢谢你们,我得到了这项工作,可能不是很有效但确实做到了:)
SELECT *
FROM (
SELECT COUNT(*) AS patients, naturopathno
FROM dbf10.patient
WHERE naturopathno is not null
GROUP BY naturopathno
ORDER BY patients DESC)
WHERE ROWNUM = 1;
有更好的方法吗?