Reputation: 13
hey guys, just having a bit of difficulty with a query, i'm trying to figure out how to show the most popular naturopath that has been visited in a centre. My tables look as follows;
Patient(patientId, name, gender, DoB, address, state,postcode, homePhone, businessPhone, maritalStatus, occupation, duration,unit, race, registrationDate , GPNo, NaturopathNo)
and
Naturopath (NaturopathNo, name, contactNo, officeStartTime, officeEndTime, emailAddress)
now to query this i've come up with
SELECT count(*), naturopathno FROM dbf10.patient WHERE naturopathno != 'NULL' GROUP BY naturopathno;
which results in;
COUNT(*) NATUROPATH
2 NP5
1 NP6
3 NP2
1 NP1
2 NP3
1 NP7
2 NP8
My question is, how would I go about selecting the highest count from this list, and printing that value with the naturopaths name? Any suggestions are very welcome,
Upvotes: 1
Views: 114
Reputation: 60312
You can use the RANK analytic function - this will assign rank "1" to the topmost naturopath, or naturopaths if there is a tie for first place:
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;
Upvotes: 1
Reputation: 13
okay figured it out, thanks guys, ive got this which does the job, probably not very efficiently but does do it :)
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;
any better ways to do this?
Upvotes: 0
Reputation: 238276
In MySQL, you could select the top row like:
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
By the way, if you're checking for null
instead of the string "NULL"
, try:
where naturopathno is not null
Upvotes: 2