返回介绍

solution / 0500-0599 / 0574.Winning Candidate / README_EN

发布于 2024-06-17 01:03:59 字数 2663 浏览 0 评论 0 收藏 0

574. Winning Candidate

中文文档

Description

Table: Candidate

+-------------+----------+
| Column Name | Type   |
+-------------+----------+
| id      | int    |
| name    | varchar  |
+-------------+----------+
id is the column with unique values 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 (column with unique values).
candidateId is a foreign key (reference column) to id from the Candidate table.
Each row of this table determines the candidate who got the ith vote in the elections.

 

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: 
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.

Solutions

Solution 1

# Write your MySQL query statement below
SELECT
  Name
FROM
  (
    SELECT
      CandidateId AS id
    FROM Vote
    GROUP BY CandidateId
    ORDER BY COUNT(id) DESC
    LIMIT 1
  ) AS t
  INNER JOIN Candidate AS c ON t.id = c.id;

Solution 2

# Write your MySQL query statement below
SELECT name
FROM
  Candidate AS c
  LEFT JOIN Vote AS v ON c.id = v.candidateId
GROUP BY c.id
ORDER BY COUNT(1) DESC
LIMIT 1;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文