我有一个显示以下内容的 MySQL 表:
ID DATE FREQUENCY
-- ---------- ---------
1 2017-08-01 1
2 2017-08-02 1
3 2017-08-03 0
4 2017-08-04 1
5 2017-08-05 1
6 2017-08-06 1
每当频率列上出现连续的 1 时,我都试图找到最简单的分组方法。然后我想展示它们。
例子
2 (There are 2 consecutive 1's)
3 (There are also 3 consecutive 1's)
谢谢
最佳答案
这是一个典型的间隙和孤岛问题。
您可以通过将记录的总体排名与其在具有相同频率的记录组中的相对排名进行比较来解决此问题。等级之间的差异为您提供了每条记录所属的组。
剩下的只是过滤和聚合频率为 1
的组。
查询:
select
min(id) min_id,
max(id) max_id,
min(date) min_date,
max(date) max_date,
count(*) streak_length
from (
select
t.*,
row_number() over(order by date) rn1,
row_number() over(partition by frequency order by date) rn2
from mytable t
) t
where frequency = 1
group by rn1 - rn2
order by min_date
Demo on DB Fiddle 使用您的示例数据:
min_id | max_id | min_date | max_date | streak_length -----: | -----: | :--------- | :--------- | ------------: 1 | 2 | 2017-08-01 | 2017-08-02 | 2 4 | 6 | 2017-08-04 | 2017-08-06 | 3
注意:窗口函数 row_number()
从 MySQL 8.0 开始可用。
关于php - 查找连续的条纹和显示计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45529917/