0

我正在尝试按开始日期和结束日期显示我酒店的免费客房

在此处输入图像描述

当我使用此代码时,它只显示出现在预订中的房间,但没有显示从未预订的房间。

SELECT room.RoomID,room.Room_Type_ID,room.Room_number,room.NumberofSpots,
 res.Data_Check_in,res.Data_Check_out FROM    

      dbo.Reservation res JOIN dbo.Room room ON room.RoomID=res.Room_ID
      WHERE NOT(res.Data_Check_in<=@p_StartData AND res.Data_Check_out>=@p_EndData)

当我使用此代码时,它会显示所有房间,甚至是保留的房间:

SELECT DISTINCT r.*
FROM dbo.Room r LEFT JOIN dbo.Reservation  res ON r.RoomID=res.Room_ID
AND  NOT(res.Data_Check_in<='2012-05-07' AND res.Data_Check_out>='2012-06-13')
AND res.Cancel=0

我应该修改什么以获得所有没有为选定日期保留的房间?

4

2 回答 2

2

请原谅在变量和列名中使用日期而不是数据。

declare @p_StartDate as Date = '2012-05-07'
declare @p_EndDate as Date = '2012-06-13'

declare @Room as Table ( Room_ID Int Identity, Room_number VarChar(5) )
insert into @Room ( Room_number ) values
  ( '101' ), ( '102' ), ( '103' ), ( '104' ), ( '105' ),
  ( '201' ), ( '202' ), ( '203' ), ( '204' ), ( '205' )

declare @Reservation as Table ( ReservationID Int Identity, Room_ID Int, Date_Check_in Date, Date_Check_out Date, Cancel Bit )
insert into @Reservation ( Room_ID, Date_Check_in, Date_Check_out, Cancel ) values
  ( 3, '2012-05-01', '2012-05-06', 0 ), -- Before.
  ( 3, '2012-06-14', '2012-07-01', 0 ), -- After.
  ( 4, '2012-05-07', '2012-06-13', 0 ), -- Matching.
  ( 5, '2012-06-01', '2012-06-05', 0 ), -- Within.
  ( 6, '2012-05-01', '2012-06-01', 0 ), -- Overlapping start.
  ( 7, '2012-06-01', '2012-06-15', 0 ), -- Overlapping end.
  ( 8, '2012-06-01', '2012-06-05', 1 ), -- Within, but cancelled.
  ( 9, '2012-06-01', '2012-06-15', 1 ), -- Overlapping, but cancelled.
  ( 10, '2012-01-01', '2012-12-31', 0 ) -- Containing.

select room.Room_ID, room.Room_number
  from @Room as room
  where not exists (
    select 42
      from @Reservation
      where Room_ID = room.Room_ID and Cancel = 0 and
        -- The date ranges overlap.
        ( ( ( @p_StartDate <= Date_Check_in ) and ( Date_Check_in <= @p_EndDate ) or
        ( @p_StartDate <= Date_Check_out ) and ( Date_Check_out <= @p_EndDate ) ) or
        -- The desired range is contained in the reserved range.
        ( ( Date_Check_in <= @p_StartDate ) and ( @p_EndDate <= Date_Check_out ) ) ) )
于 2012-05-15T22:33:58.737 回答
0

怎么样

SELECT Dr.* FROM dbo.Room r LEFT JOIN dbo.Reservation res 
ON r.RoomID=res.Room_ID
WHERE res.Room_ID IS NULL

对于从未预订过的房间。

左连接对预订的房间没有帮助,但今天没有。为此,您想要类似的东西

SELECT Room_ID FROM Reservation WHERE Data_Check_out<=? OR Data_Check_in>=?
OR (Data_Check_out<=? AND Data_Check_in<=? AND Cancel=1 )

一些好的评论。我们知道左连接会给我们“从未使用过的房间”。

如果没有取消字段,以下应该可以工作:

设置@checkindate = '2012-05-15';

设置@checkoutdate = '2012-05-17';

从预订中选择 room_id (Data_Check_in 和 Data_Check_out 之间的@checkindate 或 Data_Check_in 和 Data_Check_out 之间的 @checkoutdate)

但是取消使事情变得更加困难,因为我们需要知道所有想要的日子都是可用的。这感觉更像是需要在个别日子进行设置操作。

于 2012-05-15T19:08:58.913 回答