编写一个 SQL 查询,查找所有至少连续出现三次的数字。

  1. +----+-----+
  2. | Id | Num |
  3. +----+-----+
  4. | 1 | 1 |
  5. | 2 | 1 |
  6. | 3 | 1 |
  7. | 4 | 2 |
  8. | 5 | 1 |
  9. | 6 | 2 |
  10. | 7 | 2 |
  11. +----+-----+

例如,给定上面的 Logs 表, 1 是唯一连续出现至少三次的数字。

+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+

解决思路:一开始没有想到,是查看别人SQL进行写出来的,特地学习一下:

LeetCode180-MySQL-连续出现的数字

https://blog.csdn.net/qq_41822173/article/details/80957895
就是通过判断id是否连续,然后Num值是否相等。
我的SQL:

SELECT
    l1.Num ConsecutiveNums
FROM
    LOGS l1,
    LOGS l2,
    LOGS l3
WHERE
    l1.id = l2.id - 1
AND l2.id = l3.id - 1
AND l1.Num = l2.Num
AND l2.Num = l3.Num
GROUP BY l1.Num

其他SQL:

示例一:SELECT distinct num as ConsecutiveNums FROM(
SELECT id, num, 
@pre := @cur,
@cur := num,
@rep_ct := IF(@pre = @cur, @rep_ct + 1, 1) as rep_ct
FROM `Logs` l, (SELECT @pre := null, @cur := 0, @rep_ct := 1) init
) temp WHERE rep_ct >= 3
示例二:select distinct l1.num 'ConsecutiveNums' 
from logs l1, logs l2, logs l3
where l1.id - l2.id = 1
and l1.num = l2.num
and l2.id - l3.id = 1
and l2.num = l3.num;