首页 > 解决方案 > 如何计算同一列中价值的天数差异?

问题描述

我有这样的数据:

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 版)。请让我知道是否有解决此问题的方法。提前致谢。

标签: mysqlsqlstored-procedures

解决方案


您似乎想要枚举行然后聚合。在 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);

推荐阅读