-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path574. Winning Candidate - Locked
57 lines (49 loc) · 1.08 KB
/
574. Winning Candidate - Locked
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
574. Winning Candidate
Table: Candidate
+-----+---------+
| id | Name |
+-----+---------+
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |
| 5 | E |
+-----+---------+
Table: Vote
+-----+--------------+
| 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.
+------+
| Name |
+------+
| B |
+------+
Notes:
You may assume there is no tie, in other words there will be at most one winning candidate.
#Solution 1:
SELECT Name FROM Candidate
JOIN
(SELECT CandidateID
FROM Vote
GROUP BY CandiateId
ORDER BY Count(*) DESC
lIMIT 1) AS T1
ON Candidate.id=T1.CandidateId
#Solution 2:
SELECT Name FROM
(
SELECT Name, COUNT(*) AS cnt
FROM Candidate JOIN Vote AS T1
ON Candidate.id=Vote.CandidateId
GROUP BY T1.CandidateID
ORDER BY cnt DESC
LIMIT 1) AS T2