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




Related Posts

Find Median Given Frequency Of Numbers Problem

LeetCode 571. Write a query to find the median of...

Find Cumulative Salary Of An Employee Problem

LeetCode 579. Write a SQL to get the cumulative sum...

Get Highest Answer Rate Question Problem

LeetCode 578. Write a sql query to identify the question...

Winning Candidate Problem

LeetCode 574. Write a sql to find the name of...

Managers With At Least 5 Direct Reports Problem

LeetCode 570. Given the Employee table, write a SQL query...

Employee Bonus Problem

LeetCode 577. Select all employee’s name and bonus whose bonus...