我在弄清楚如何使用 MySQL 计算不同日期范围之间的总天数时遇到问题。
我需要计算不同日期范围之间的总天数,而不是包含彼此日期范围的天数。
数据示例:
来自 | 到 |
---|---|
2021/08/28 | 2021/09/29 |
2021/08/29 | 2021/09/01 |
2021/09/01 | 2021/09/01 |
日期范围示例和输出
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
答案 0 :(得分:1)
可能最简单的方法是递归 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;
请注意,from
和 to
是非常糟糕的列名称,因为它们是 SQL 关键字。
编辑:
在 MySQL 5.7 中,您可以使用计数表——数字表。
假设您的原始表在最宽的时间跨度内有足够的行,您可以使用:
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`;
如果您的桌子真的很大,您可能需要在最宽的时间段内使用 limit
。