Description
Table: Candidate
| Column Name | Type |
|---|---|
| id | int |
| name | varchar |
idis the column with unique values for this table.- Each row of this table contains information about the
idand thenameof a candidate.
Table: Vote
| Column Name | Type |
|---|---|
| id | int |
| candidateId | int |
idis an auto-increment primary key (column with unique values).candidateIdis a foreign key (reference column) toidfrom theCandidatetable.- Each row of this table determines the candidate who got the
ith vote in the elections.
Problem Statement
Write a solution 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 result format is in the following example.
Example 1:
Input:
Candidatetable:
| id | name |
|---|---|
| 1 | A |
| 2 | B |
| 3 | C |
| 4 | D |
| 5 | E |
Votetable:
| 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.
Solution
This is typical aggregation problem. Here, the problem can be divided into following.
- Find the
candidateIdfromVotetable which occurs the most. This can be done using aggregation. - Associate the
nameto thiscandidateIdand output only first name.
1SELECT name FROM (
2 SELECT name, COUNT(1) votes
3 FROM Candidate
4 JOIN Vote
5 ON Candidate.id = Vote.candidateId
6 GROUP BY name
7 ORDER BY votes DESC
8 LIMIT 1
9) tmp;


Comments