简体   繁体   中英

How to do the max count part in SQL?

I was told to Find out which occupation has the greatest number of patients with conditionID=MC8 I dk how to do the greatest part..... Here my code right now

SELECT occupation
FROM Patient
WHERE EXISTS                  
(SELECT PatientID FROM PatientMedcon
    Where conditionID=’MC8’)    
GROUP BY occupation
HAVNG count(occupation) = (Select max(occupation)
From Patient

You should approach these types of queries using regular joins and then add additional factors. The following gets the count of patients for each occupation with that condition:

SELECT occupation, COUNT(*)
FROM Patient p JOIN
     PatentMedcon pm
     ON p.PatientId = pm.PatientId and
        pm.conditionId = 'MC8'
GROUP BY occupation
ORDER BY COUNT(*) DESC;

If you want the top row, that depends on the database. It might be select top 1 , limit 1 at the end, fetch first 1 rows only at the end, or even something else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM