【问题标题】:how to select a date if it is already between two values sql server如果日期已经在两个值之间,如何选择日期sql server
【发布时间】:2019-11-01 15:48:03
【问题描述】:

我正在尝试在 2 个不同列中的 2 个不同日期之间进行选择,并且我认为在遇到此问题之前我已经理解了如何操作。我想我最好提供一个例子:

房间有一个入住日期和一个退房日期(与酒店问题相关)。我想选择不在 inDate 和 outDate 之间的房间。因此我可以使用这个查询:

select * from room where  inDate and outDate not between '2019-06-19' and '2019-06-26';

让我们假设我们有一个带有inDate = '2019-06-18'outDate = '2019-06-21' 的房间。

我的问题是,知道用户无法预订该房间,因为当时房间不可用,这可能是正确的查询?因为如果我们使用前面提到的查询,那个房间将是可用的,但显然不是。

我在此页面上看到很多页面都在询问类似的问题,但我尝试不创建重复项。如果这是重复的,请提前抱歉,我希望我自己解释正确。

【问题讨论】:

标签: sql sql-server date between


【解决方案1】:

如果您正在寻找可用房间,那么逻辑如下所示:

select *
from room r
where not (inDate <= '2019-06-26' and
           outDate >= '2019-06-19'
          );

两个时间段(例如房间预订和间隔)重叠,每个时间段开始于另一个结束之前。 not 是因为您想要没有预订的房间。

实际上,上面的内容看起来不太正确。您应该有一张用于房间的桌子和一张用于预订的桌子。然后查询将如下所示:

select r.*
from rooms r
where not exists (select 1
                  from reservations re
                  where re.room_id = r.room_id and
                        re.inDate <= '2019-06-26' and
                        re.outDate >= '2019-06-19'
                 );

【讨论】:

  • 实际上我的真实查询看起来与您的相似:SELECT distinct room.* FROM room, booking where room.id not in (select idroom from booking where inDate and outDate NOT between '2019-06-19'和 '2019-06-20') order by room.price Desc;但似乎我认为我可以使用 between 子句来选择它们。会给它一些尝试和思考,我会用结果回复你。根据我所尝试的解决问题,但我想确保它。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 2019-10-09
  • 1970-01-01
  • 2021-11-30
  • 2011-07-04
  • 1970-01-01
相关资源
最近更新 更多