表 my_numbers 的 num 字段包含很多数字,其中包括很多重复的数字。
你能写一个 SQL 查询语句,找到只出现过一次的数字中,最大的一个数字吗?
+---+
|num|
+---+
| 8 |
| 8 |
| 3 |
| 3 |
| 1 |
| 4 |
| 5 |
| 6 |
对于上面给出的样例数据,你的查询语句应该返回如下结果:
+---+
|num|
+---+
| 6 |
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/biggest-single-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
审题:查找只出过一次的最大的数字。
思考:查找只出现过一次的数字。按照分组,查找每个组只有一个数字的组,然后排序取第一个。
解题:
找出仅出过一次的最大数。
对数字分组,每组计数,选出计数等于1的行。
从多个数字再取最大值。
select max(A.num) as `num`
from
(
select M.num as `num`
from my_numbers as M
group by M.num
having count(M.num)=1
) as A
有一种易错的方法。
select A.num
from
(
select M.num as `num`
from my_numbers as M
group by M.num
having count(M.num)=1
order by M.num desc
limit 0,1
) as A
思路上是对的,但当 没有只出现一次的数字 时,表A为空但不是NULL。不符合题目的要求。
修改为下面即可。但这样的修改还不及上面的直接。
select max(A.num) as `num`
from
(
select M.num as `num`
from my_numbers as M
group by M.num
having count(M.num)=1
order by M.num desc
limit 0,1
) as A
也可修改为如下。
应用IFNULL。当第一个参数不为NULL时,返回第一个参数,否则返回第二个参数。
SELECT IFNULL(
(
select M.num
from my_numbers as M
group by M.num
having count(M.num)=1
order by M.num desc
limit 0,1
)
, NULL
) AS `num`
由于本例中表只有一列。
上述代码还可简化为:
SELECT IFNULL(
(
SELECT *
from my_numbers as M
group by M.num
having COUNT(*)=1
order by M.num desc
limit 0,1
)
, NULL
) AS `num`
方法二:
方法:使用子查询 和 MAX()
函数【通过】
算法
使用子查询找出仅出现一次的数字。
SELECT
num
FROM
`number`
GROUP BY num
HAVING COUNT(num) = 1;
然后使用 MAX()
函数找出其中最大的一个。
SELECT
MAX(num) AS num
FROM
(SELECT
num
FROM
number
GROUP BY num
HAVING COUNT(num) = 1) AS t
知识点:
havaing count() 查询分组后数量