-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path574-WinningCandidate.sql
More file actions
80 lines (80 loc) · 1.89 KB
/
574-WinningCandidate.sql
File metadata and controls
80 lines (80 loc) · 1.89 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
-- 574. Winning Candidate
-- Table: Candidate
--
-- +-------------+----------+
-- | Column Name | Type |
-- +-------------+----------+
-- | id | int |
-- | name | varchar |
-- +-------------+----------+
-- id is the primary key column for this table.
-- Each row of this table contains information about the id and the name of a candidate.
--
-- Table: Vote
--
-- +-------------+------+
-- | Column Name | Type |
-- +-------------+------+
-- | id | int |
-- | candidateId | int |
-- +-------------+------+
-- id is an auto-increment primary key.
-- candidateId is a foreign key to id from the Candidate table.
-- Each row of this table determines the candidate who got the ith vote in the elections.
--
-- Write an SQL query to report the name of the winning candidate (i.e., the candidate who got the largest number of votes).
-- The test cases are generated so that exactly one candidate wins the elections.
-- The query result format is in the following example.
--
-- Example 1:
--
-- Input:
-- 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 |
-- +----+-------------+
-- Output:
-- +------+
-- | name |
-- +------+
-- | B |
-- +------+
-- Explanation:
-- Candidate B has 2 votes. Candidates C, D, and E have 1 vote each.
-- The winner is candidate B.
--
# Write your MySQL query statement below
SELECT
c.name
FROM
Candidate AS c,
(
SELECT
COUNT(*) AS num,
candidateId
FROM
Vote
GROUP BY
candidateId
) AS v
WHERE
c.id = v.candidateId
ORDER BY
v.num DESC
LIMIT 1