1. 程式人生 > >180. 連續出現的數字

180. 連續出現的數字

連續出現的數字

編寫一個 SQL 查詢,查詢所有至少連續出現三次的數字。
±—±----+
| Id | Num |
±—±----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
±—±----+
例如,給定上面的 Logs 表, 1 是唯一連續出現至少三次的數字。
±----------------+
| ConsecutiveNums |
±----------------+
| 1 |
±----------------+

思路1:

多表查詢:直接在三個表的例項中查詢,然後把四個條件限定上,就可以返回正確結果了

MS-SQL Server
實現1:

select distinct(l1.Num) as '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

思路2:

聯表查詢:
用l1分別和l2, l3內交,l1和l2的Id下一個位置比,l1和l3的下兩個位置比,然後將Num都相同的數字返回即可

實現2:

select distinct(l1.Num) as 'ConsecutiveNums' from Logs l1
    join Logs l2 on l1.Id=l2.Id-1
    join Logs l3 on l1.Id=l3.Id-2
    where l1.Num=l2.Num and l2.Num=l3.Num