我假设你想知道的东西比如在开始和结束之间的每个日期有多少个房间被填满。这里的“诀窍”是,从开始/结束之间的很长一段时间将重复一天或一周,并且/或者一周的结束日可能小于一周的开始日。所以,我有:
- 产生100000个日期(1每行)的列表
- 加入你的表的开始/结束
- 转换的各参加行的周数日之间的日期算
- 左接合到清单1至7,并计数步骤中的行3
注意:如果END_DATE是“签出日期”,那么它可能有必要扣除1天从每个记录要补偿(这不是在下面做)。
这种方法可用于审查在这里SQL Fiddle
的MySQL 5.6架构设置:
CREATE TABLE Table1
(`id` int, `start_date` datetime, `end_date` datetime)
;
INSERT INTO Table1
(`id`, `start_date`, `end_date`)
VALUES
(1, '2017-09-21 00:00:00', '2017-10-07 00:00:00'), ## added this row
(1, '2017-10-01 00:00:00', '2017-10-07 00:00:00'),
(2, '2017-10-04 00:00:00', '2017-10-07 00:00:00'),
(3, '2017-10-06 00:00:00', '2017-10-08 00:00:00')
;
查询:
set @commence := str_to_date('2000-01-01','%Y-%m-%d')
select
w.dy
, count(t.wdy)
from (
select 1 dy union all select 2 dy union all select 3 dy union all
select 4 dy union all select 5 dy union all select 6 dy union all select 7 dy
) w
left join (
select DAYOFWEEK(cal.dy) wdy
from (
select adddate(@commence ,t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) dy
from ( select 0 i union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t0
cross join (select 0 i union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t1
cross join (select 0 i union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t2
cross join (select 0 i union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t3
cross join (select 0 i union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) t4
) cal
INNER JOIN Table1 t on cal.dy between t.start_date and t.end_date
) t on w.dy = t.wdy
group by
w.dy
Results:
| dy | count(t.wdy) |
|----|--------------|
| 1 | 4 |
| 2 | 3 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
| 6 | 6 |
| 7 | 6 |
另见:How to get list of dates between two dates in mysql select query那里接受的答案是一组交叉的基础上加入产生从提名日起10万周的日期。然而,我修改了语法(显式交叉连接语法),一个参数作为起点,并使用union all
来提高效率。
使用日历表(包含您需要的所有日期)并使用BETWEEN条件将其加入到表中。 –
不幸的是,10月份是在星期天开始的。 – Strawberry