返回介绍

solution / 0600-0699 / 0619.Biggest Single Number / README_EN

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

619. Biggest Single Number

中文文档

Description

Table: MyNumbers

+-------------+------+
| Column Name | Type |
+-------------+------+
| num     | int  |
+-------------+------+
This table may contain duplicates (In other words, there is no primary key for this table in SQL).
Each row of this table contains an integer.

 

A single number is a number that appeared only once in the MyNumbers table.

Find the largest single number. If there is no single number, report null.

The result format is in the following example.

 

Example 1:

Input: 
MyNumbers table:
+-----+
| num |
+-----+
| 8   |
| 8   |
| 3   |
| 3   |
| 1   |
| 4   |
| 5   |
| 6   |
+-----+
Output: 
+-----+
| num |
+-----+
| 6   |
+-----+
Explanation: The single numbers are 1, 4, 5, and 6.
Since 6 is the largest single number, we return it.

Example 2:

Input: 
MyNumbers table:
+-----+
| num |
+-----+
| 8   |
| 8   |
| 7   |
| 7   |
| 3   |
| 3   |
| 3   |
+-----+
Output: 
+------+
| num  |
+------+
| null |
+------+
Explanation: There are no single numbers in the input table so we return null.

Solutions

Solution 1: Grouping and Subquery

We can first group the MyNumbers table by num and count the number of occurrences of each number. Then, we can use a subquery to find the maximum number among the numbers that appear only once.

# Write your MySQL query statement below
SELECT MAX(num) AS num
FROM
  (
    SELECT num
    FROM MyNumbers
    GROUP BY 1
    HAVING COUNT(1) = 1
  ) AS t;

Solution 2: Grouping and CASE Expression

Similar to Solution 1, we can first group the MyNumbers table by num and count the number of occurrences of each number. Then, we can use a CASE expression to find the numbers that appear only once, sort them in descending order by number, and take the first one.

# Write your MySQL query statement below
SELECT
  CASE
    WHEN COUNT(1) = 1 THEN num
    ELSE NULL
  END AS num
FROM MyNumbers
GROUP BY num
ORDER BY 1 DESC
LIMIT 1;

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

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

发布评论

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