LeetCode 574. Winning Candidate SQL Solution
Problem
LeetCode SQL Problem
- Winning Candidate
Candidate table
id | Name |
---|---|
1 | A |
2 | B |
3 | C |
4 | D |
5 | E |
Vote table
id | CandidateId |
---|---|
1 | 2 |
2 | 4 |
3 | 3 |
4 | 2 |
5 | 5 |
Solution
- MySQL
- TSQL
Winning Candidate
-- Find the name of the winning candidate
-- Use LIMIT clause as we're told there will be no tie
SELECT C.Name
FROM Vote AS V
INNER JOIN Candidate AS C ON V.CandidateId = C.id
GROUP BY V.CandidateId
,C.Name
ORDER BY count(*) DESC
LIMIT 1
Winning Candidate
-- Find the name of the winning candidate
-- Use TOP clause as we're told there will be no tie
SELECT TOP 1 C.Name
FROM Vote AS V
INNER JOIN Candidate AS C ON V.CandidateId = C.id
GROUP BY V.CandidateId
,C.Name
ORDER BY count(*) DESC
Query Output
Name |
---|
B |