編寫一個 SQL 查詢,查找所有至少連續出現三次的數字。
+----+-----+
| Id | Num |
+----+-----+
| 1 ?| ?1 ?|
| 2 ?| ?1 ?|
| 3 ?| ?1 ?|
| 4 ?| ?2 ?|
| 5 ?| ?1 ?|
| 6 ?| ?2 ?|
| 7 ?| ?2 ?|
+----+-----+
例如,給定上面的 Logs 表, 1 是唯一連續出現至少三次的數字。
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1 ? ? ? ? ? ? ? |
+-----------------+
思路:自連接,注意去重。
select distinct A.Num as 'ConsecutiveNums'
from Logs as A,Logs as B,Logs as C
where A.Id-1=B.Id and B.Id-1=C.Id and A.Num=B.Num and B.Num=C.Num;
?