Winning Candidate Problem
Description
LeetCode Problem 574.
Table: Candidate
1
2
3
4
5
6
7
8
9
+-----+---------+
| id | Name |
+-----+---------+
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |
| 5 | E |
+-----+---------+
Table: Vote
1
2
3
4
5
6
7
8
9
10
11
+-----+--------------+
| id | CandidateId |
+-----+--------------+
| 1 | 2 |
| 2 | 4 |
| 3 | 3 |
| 4 | 2 |
| 5 | 5 |
+-----+--------------+
id is the auto-increment primary key,
CandidateId is the id appeared in Candidate table.
Write a sql to find the name of the winning candidate, the above example will return the winner B.
1
2
3
4
5
+------+
| Name |
+------+
| B |
+------+
Notes: You may assume there is no tie, in other words there will be only one winning candidate.
MySQL Solution
1
2
3
4
5
6
7
8
select name as 'Name'
from Candidate
join (select Candidateid
from Vote
group by Candidateid
order by count(*) desc
limit 1) as winner
where Candidate.id = winner.Candidateid
LeetCode Database - Medium
LeetCode 177
LeetCode 178
LeetCode 180
LeetCode 184
LeetCode 534
LeetCode 550
LeetCode 570
LeetCode 574
LeetCode 578
LeetCode 580
LeetCode 585
LeetCode 602
LeetCode 608
LeetCode 612
LeetCode 614
LeetCode 626
LeetCode 1045
LeetCode 1070
LeetCode 1077
LeetCode 1098
LeetCode 1107
LeetCode 1112
LeetCode 1126
More LeetCode Database
MySQL Tutorials