我有下表
Id | cont
----------
1 | 0
2 | 1
3 | 0
4 | 1
5 | 2
6 | 3
7 | 0
8 | 1
9 | 2
10 | 0
11 | 1
12 | 2
13 | 3
14 | 4
我需要获得序列号从2以上的岛屿,并删除间隙。
结果应为
Id | cont
----------
5 | 2
6 | 3
12 | 2
13 | 3
14 | 4
答案 0 :(得分:1)
假设ID将单调增加,您可以通过几个步骤实现这一目标。
首先,对于每个数字,你得到第一个前一个零
select t1.ID, t1.cont, max(t2.ID) max_id
from yourTable t1
join yourTable t2
on t1.id >= t2.id
where t2.cont = 0
group by t1.ID, t1.cont
然后使用它来获得多于1行的序列
select t1.max_id, count(*)
from (
select t1.ID, t1.cont, max(t2.ID) max_id /* STEP 1 */
from yourTable t1
join yourTable t2
on t1.id >= t2.id
where t2.cont = 0
group by t1.ID, t1.cont
) t1
where cont > 1
group by t1.max_id
having count(*) > 1
最后加入这两个来获取你想要的id和值
select t1.id, t1.cont
from (
select t1.ID, t1.cont, max(t2.ID) max_id /* STEP 1 */
from yourTable t1
join yourTable t2
on t1.id >= t2.id
where t2.cont = 0
group by t1.ID, t1.cont
) t1
join (
select t1.max_id, count(*) /* STEP 2 */
from (
select t1.ID, t1.cont, max(t2.ID) max_id
from yourTable t1
join yourTable t2
on t1.id >= t2.id
where t2.cont = 0
group by t1.ID, t1.cont
) t1
where cont > 1
group by t1.max_id
having count(*) > 1
) t2
on t1.max_id = t2.max_id
where t1.cont > 1
您可以在 here
中查看此查询答案 1 :(得分:1)
Or just..
SELECT DISTINCT x.*
FROM my_table x
JOIN my_table y
ON (y.id = x.id - 1 OR y.id = x.id + 1)
AND y.cont >= 2
WHERE x.cont >= 2;