views:

54

answers:

3

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,

+2  A: 

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
Andomar
sorry about the tags, im using oracle 10g
bu0489
A: 

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?

bu0489
yes - if there's a tie for top place, this query picks the first one that appears
Jeffrey Kemp
+1  A: 

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;
Jeffrey Kemp
Although this wouldn't give the Naturopath name that the OP is after.
dalton
thanks dalton, I've updated it.
Jeffrey Kemp