我读了很多关于寻找间隙的好答案(这里,这里,这里(,但我仍然不知道如何找到最小预定义大小的间隙。
在我的案例中,空白是HE没有名字顺序的条目。
我还需要像示例中那样,从表格开头开始查找差距。
任何人都可以帮助编写一个漂亮干净的SQL语句,该语句可以简单地更改以获得预定义的最小间隙大小
预期输出示例:
+-----------+----+ +----------------+ +----------------+ +----------------+
| name | HE | | GAPS >= 1 | | GAPS >= 2 | | GAPS >= 3 |
+-----------+----+ +-----------+----+ +-----------+----+ +-----------+----+
| | 1 | | name | HE | | name | HE | | name | HE |
| JohnDoe01 | 2 | +-----------+----+ +-----------+----+ +-----------+----+
| JohnDoe02 | 3 | | | 1 | | | 4 | | | 12 |
| | 4 | | | 4 | | | 5 | | | 13 |
| | 5 | | | 5 | | | 9 | | | 14 |
| JohnDoe03 | 6 | | | 9 | | | 10 | +-----------+----+
| JohnDoe04 | 7 | | | 10 | | | 12 |
| JohnDoe05 | 8 | | | 12 | | | 13 |
| | 9 | | | 13 | | | 14 |
| | 10 | | | 14 | +-----------+----+
| JohnDoe06 | 11 | +-----------+----+
| | 12 |
| | 13 |
| | 14 |
| JohnDoe07 | 15 |
+-----------+----+
您可以识别间隙以及起点和终点。要识别差距,请计算非差距的数量并汇总:
select min(he), max(he), count(*) as size
from (select t.*, count(name) over (order by he) as grp
from t
) t
where name is null
group by grp;
然后,您可以使用having
对特定大小的间隙进行筛选,例如2
:
having count(*) >= 2
例如。
这总结了间隙,每行一个。事实上,这对我来说似乎比每行单独一行更有用。
编辑:
如果你真的想要原始的行,你可以做:
select t.*
from (select t.*,
max(he) filter (where name is not null) over (order by he) as prev_he,
min(he) filter (where name is not null) over (order by he desc) as next_he,
max(he) over () as max_he
from t
) t
where name is null and
(max(next_he, max_he + 1) - coalesce(prev_he, 0) - 1) >= 2;
编辑II:
在旧版本的MySQL/MariaDB中,您可以使用变量:
select min(he), max(he), count(*) as size
from (select t.*,
(@grp := @grp + (name is not null)) as grp
from (select t.* from t order by he) t cross join
(select @grp := 0) params
) t
where name is null
group by grp;