简体   繁体   English

计算多个日期范围之间的总天数

[英]Calculating total of days between multiple date ranges

I have a problem figuring out how to calculate total days between different date ranges using MySQL.我在弄清楚如何使用 MySQL 计算不同日期范围之间的总天数时遇到问题。

I need to count total of days between different date ranges without days that include each other date range.我需要计算不同日期范围之间的总天数,而没有包含彼此日期范围的天数。

Data example:数据示例:

from to
2021/08/28 2021/08/28 2021/09/29 2021/09/29
2021/08/29 2021/08/29 2021/09/01 2021/09/01
2021/09/01 2021/09/01 2021/09/01 2021/09/01

Date ranges example and output日期范围示例和 output

Dates   2021-08-28  2021-08-29  2021-08-30  2021-08-31  2021-09-01  2021-09-02  2021-09-03  2021-09-04 
Range1  |--------------------|         
Range2                                      |--------------------|         
Range3                                                                          |--------------------|         

Total Days: 6

Dates   2021-08-28  2021-08-29  2021-08-30  2021-08-31  2021-09-01  2021-09-02  2021-09-03  2021-09-04 
Range1  |--------------------|         
Range2              |--------------------------------------------|         
Range3                                                  |--------|         

Total Days: 5

Possibly the simplest method is a recursive CTE:可能最简单的方法是递归 CTE:

with recursive dates as (
      select `from`, `to`
      from t
      union all
      select `from` + interval 1 day, `to`
      from dates
      where `from` < `to`
     )
select count(distinct `from`)
from dates;

Note that from and to are really bad names for columns because they are SQL keywords.请注意, fromto是非常糟糕的列名称,因为它们是 SQL 关键字。

EDIT:编辑:

In MySQL 5.7, you can use a tally table -- a table of numbers.在 MySQL 5.7 中,您可以使用计数表——数字表。

Assuming your original table has enough rows for the widest time span, you can use:假设您的原始表在最宽的时间跨度内有足够的行,您可以使用:

select count(distinct `from` + interval (n - 1) day)
from t cross join
     (select (@rn := @rn + 1) as n
      from t cross join
           (select @rn := 0) params
     )  n
     on `from` + interval (n - 1) day <= `to`;

If your table is really big, you might want a limit for the widest time period.如果您的表真的很大,您可能需要一个最宽时间段的limit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM