简体   繁体   中英

In SQL, how do I get the row with the maximum value for a particular column?

I have a query:

SELECT COUNT(*) as votes, a.member_id 
FROM ballots a
WHERE ballot_id = 1
GROUP BY a.member_id

which yields something like:

votes  member_id
1      paul
5      mike
3      noynoy
10     andy
2      noel

I'd like to be able to get the row "andy" because he got the highest "votes".

How do I change my query to do this?

Thanks in advance for your help :)

You can order it from highest to lowest votes using ORDER BY and then DESC for descending order. Then LIMIT the results to only one row (ie the highest).

SELECT COUNT(*) as votes, a.member_id 
FROM ballots a
WHERE ballot_id = 1
GROUP BY a.member_id
ORDER BY votes DESC
LIMIT 1
SELECT COUNT(*) as votes, a.member_id 
FROM ballots a
WHERE ballot_id = 1
GROUP BY a.member_id
ORDER BY COUNT(*) DESC 
LIMIT 1
SELECT COUNT(*) as votes, a.member_id 
FROM ballots a 
WHERE ballot_id = 1 
GROUP BY a.member_id
ORDER BY votes DESC
LIMIT 1
SELECT COUNT(*) as votes, a.member_id 
FROM ballots a 
WHERE ballot_id = 1 
GROUP BY a.member_id
ORDER BY COUNT(*) DESC
LIMIT 1

Using COUNT() will not select all the rows if the maximum value repeats. My suggestion is to use MAX()

SELECT *
FROM ballots a
WHERE votes = (SELECT max(votes) FROM ballots)

might be easier to get with a dedicated view for counting the votes

CREATE VIEW v_votes AS 
  SELECT member_id, ballot_id,  COUNT(*) AS votes FROM ballots GROUP BY member_id

and then use a HAVING clause

SELECT * FROM v_votes HAVING MAX(votes)

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