I have a problem figuring out how to calculate total days between different date ranges using 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/09/29 |
2021/08/29 | 2021/09/01 |
2021/09/01 | 2021/09/01 |
Date ranges example and 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:
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.
EDIT:
In MySQL 5.7, you can use a tally table -- a table of numbers.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.