mysql - 如何计算同一列中价值的天数差异?
问题描述
我有这样的数据:
select * from date_table;
startdate
2018-08-22
2018-08-24
2018-08-27
2018-08-29
2018-08-31
2018-09-05
2018-09-07
2018-09-10
我已经写了这个查询,它只给出了天的差异
CREATE temporary TABLE if not exists results AS (
select t.startdate, datediff(
(select min(t1.startdate)
from
date_table t1 where
t1.startdate>t.startdate),
t.startdate ) days_diff
from
date_table t) ;
select * from results:
上面的查询给出的结果为:
startdate days_diff
2018-08-22 2
2018-08-24 3
2018-08-27 2
2018-08-29 2
2018-08-31 5
2018-09-05 2
2018-09-07 3
2018-09-10
但我想要这样的结果:
startdate enddate days_diff
2018-08-22 2018-08-24 2
2018-08-27 2018-08-29 2
2018-08-31 2018-09-05 5
2018-09-07 2018-09-10 3
我正在使用 MySQL(5.6 版)。请让我知道是否有解决此问题的方法。提前致谢。
解决方案
您似乎想要枚举行然后聚合。在 8.0 之前的版本中,您可以使用变量。剩下的就是聚合:
select min(start_date) as start_date, max(start_date) as end_date
from (select (@rn := @rn + 1) as seqnum, t.*
from (select t.* from date_table t order by start_date) t cross join
(select @rn := 0) params
) t
group by floor((seqnum - 1) / 2);
推荐阅读
- python - 如何使用 Lambda 代理向 AWS Lambda 抛出 HTTP 错误代码?
- python - Python startswith() 不删除所有匹配项
- ruby-on-rails - 使用 gem globalize,如何切换区域设置仅用于输入而不是整个页面?
- sql-server - Visual Studio 中指定的用于连接 SQL Server 的连接字符串在哪里?
- angular - 获取地图
不是 Angular 测试中的功能 - javascript - 如何使用 Javascript 更改 API 响应
- python - sympy 中的向量方程
- node.js - Promise.all 不等待所有响应 Azure Node.js 函数
- kubernetes-helm - 错误:无法获取 helm test myproject --logs 的 pod 日志
- angular - 如何在角度单元测试中检查复选框