我的桌子上有这样的预订:
+------------+----------+----------+
| date | time | duration |
+------------+----------+----------+
| 2014-05-10 | 13:00:00 | 60 |
| 2014-05-13 | 09:00:00 | 60 |
| 2014-05-13 | 10:00:00 | 60 |
| 2014-05-13 | 13:00:00 | 60 |
| 2014-05-13 | 17:00:00 | 60 |
| 2014-05-13 | 18:00:00 | 60 |
| 2014-05-14 | 09:00:00 | 720 |
| 2014-05-15 | 09:00:00 | 60 |
| 2014-05-15 | 11:00:00 | 60 |
| 2014-05-15 | 12:00:00 | 60 |
+------------+----------+----------+
所以,我可以预订一小时或全天预订。
现在,我想创建一个小时的新预订,我想知道特定月份的哪些天有空闲时间。我不想知道所有免费插槽(就像其他SO问题一样),我只是想知道哪些天可以分配这个预订。 因此,知道开始和结束时间,新预订时间和月份,我需要一个可以返回这样的SQL查询:
+------------+
| free_days |
+------------+
| 2014-05-01 |
| ... |
| 2014-05-08 |
| 2014-05-09 |
| 2014-05-10 |
| 2014-05-11 |
| 2014-05-12 |
| 2014-05-13 |
| 2014-05-15 |
| ... |
| 2014-05-31 |
+------------+
2014-05-14因为有一天的全天预订而丢失,但如果有例如12个一小时的预订则可能会丢失其他日子。
我看过其他SO文章,但我无法适应它。有什么想法吗?
答案 0 :(得分:0)
我只在Sql server中测试过这个,虽然我认为应该非常相似:
create table #AllDatesInRange
(
date datetime
)
declare @maxDate datetime
declare @currentdate datetime
set @maxDate = (select max(date) from table_1)
set @currentdate = (select min(date) from table_1)
while @currentdate <= @maxDate
begin
insert #AllDatesInRange(date) values(@currentdate)
set @currentdate = dateadd(day,1,@currentdate)
End
--missing dates
SELECT A.date, 'Free All Day' as [Free slots] from #AllDatesInRange A
LEFT JOIN table_1 B ON
A.date = B.date
WHERE B.date IS NULL
UNION All
select date, 'One or more slots free' as [Free slots] FROM table_1
group by Date
having sum(duration) < 720