sql - 在sqlite中查找最长的条纹

标签 sql sqlite

请帮我获取条纹数据。我有目标成就表

表测试

dt

2017-01-01
2017-01-02
2017-01-03. //3 days end of streak
2017-02-10 // 1 day
2017-02-15
2017-02-16
2017-02-17
2017-02-18 //4 days

我在 MySQL 中试过这个
Select dt, (select count(*) from test as t1 where t1.dt < t2.dt and datediff(t2.dt,t1.dt) =1) as str 
from test as t2

并得到
Dt         str
2017-01-01  0
2017-01-02  1
2017-01-03  2
2017-02-10  0
2017-02-15  0
2017-02-16  1
2017-02-17  2
2017-02-18  3

有没有可能得到这样的东西
Dt.        Str 
2017-01-03  3
2017-02-10  1
2017-02-18  4

并得到它的最大?

最佳答案

您可以从当前行的日期中减去行号(即行数 <= 当前行的日期),以将具有一天差异的连续行分类到同一组中。那么它只是一个分组操作来计算计数。

select max(dt) as dt, count(*) as streak
from (select t1.dt
      ,date(t1.dt,-(select count(*) from t t2 where t2.dt<=t1.dt)||' day') as grp
      from t t1
     ) t
group by grp 

运行内部查询以查看组是如何分配的。

关于sql - 在sqlite中查找最长的条纹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44056555/

相关文章:

sql - 用 SQL 除以零

android - android项目中SQLite向表中插入一条记录的错误

python - Python 或 Bash 或 CLI 中的 SQLite 数据更改通知回调

database - unity 使用 SQLite 数据库构建 webGL

php - MySQL 与 FOREIGN KEYS 的多对多关系

mysql - 如何结合两个更新

sql - 使用函数时在 Oracle View 中保留类型信息?

sql - 在 psql.exe 中插入失败(从 powershell 创建)

sqlite - PostgreSQL 中 SQLite 日期时间函数的等价物是什么?

AndroidexecuteSQL 不工作(INSERT INTO TABLE2 SELECT * FROM TABLE1)