php - 查找连续的条纹和显示计数

标签 php mysql gaps-and-islands

我有一个显示以下内容的 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/

相关文章:

php - 在 Laravel 5.x 中获取 "class does not exist"

php - 在 CentOs 上安装 squirrelmail

Mysql 差距和孤岛问题?

sql - 如何填补 Postgres 查询中的时间戳空白?

SQL 列表到范围结果

php - Corcel/Laravel Eloquent 模型获取多个 post_types 结果 | WordPress

Java - Mysql异常不是unicode

mysql - 使用 jooq 计算多列的总和并与另一个表连接

python - MySQLdb 连接问题

php - MySQL 列值到数组。结果是错误的值