I have a database in which people submit votes for people in different places. At a given time, I want to find out who has the most votes at each place. (A person can be voted at two different places)
This is the SQL I have so far:
SELECT placeId, userVotedId, cnt
FROM
(SELECT uvo.userVotedId, p.placeId, count(*) as cnt
FROM users as u, users_votes as uvo, places as p
WHERE u.userId = uvo.userVotedId
AND p.placeId = uvo.placeId
GROUP BY userVotedId, placeId)
AS RESULT
which gives me this result:

Now, these are the rows I REALLY want:

What’s missing in my query so I can get this?
-
I want one result per place. So I should see only distinct placeIds, with the userVotedId who received the most votes.
-
In the event of a tie, a random winner will do!
Seems like you need one more aggregate. Use theMAX()aggregate on yourcntvalue andGROUP BY placeId, userVotedId:Note: I changed your query to use
JOINsyntax instead of the commas between the tables.Edit, based on your comment the following should work:
See SQL Fiddle with Demo
The result is:
Edit #2, if you want a random number returned if there is a tie, then you can use user variables:
See SQL Fiddle with Demo