# int32bit / leetcode

Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
..
Failed to load latest commit information.
consecutiveNumbers.sql
when.sql

## Consecutive Numbers

Write a SQL query to find all numbers that appear at least three times consecutively.

``````+----+-----+
| Id | Num |
+----+-----+
| 1  |  1  |
| 2  |  1  |
| 3  |  1  |
| 4  |  2  |
| 5  |  1  |
| 6  |  2  |
| 7  |  2  |
+----+-----+
``````

For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times.

## Solution 1

```select log1.Num from Logs log1
join Logs log2
on log1.Id + 1 = log2.Id and log1.Num = log2.Num
group by log1.Num
having count(log1.Num) >= 2;```

## Solution 2

```select distinct a.Num
from Logs a, Logs b,Logs c
where a.Id=b.Id+1 and a.Num=b.Num and b.Id=c.Id+1 and b.Num=c.Num;```

## Solution 3

```select Num from (
SELECT
Num,
CASE
WHEN @prevNum = Num THEN @count := @count + 1
WHEN @prevNum := Num THEN @count := 1
END n
FROM Logs, (select @prevNum := NULL) initPrevNum, (select @count := 1) initCount
) as result where result.n >= 3;```

## mysql case 语句

```select Num,
case
when Num % 2 = 0 then "Even"
when Num % 2 = 1 then "Odd"
end Numtype
from Logs;```
You can’t perform that action at this time.