SQL query to search for room availability

前端 未结 4 1607
你的背包
你的背包 2020-12-05 17:20

The follow tables I have are:

 CUSTOMERS (CustomerID, firstname, surname etc)
 ROOMS (RoomID, RoomType, Description)
 BOOKING (BookingID, CustomerID, Arriva         


        
4条回答
  •  -上瘾入骨i
    2020-12-05 17:54

    You have the following cases

    The user's selected period:
    --------[---------]-------
    Booking no1 
    [-----]-------------------
    Booking no2
    --------------------[----]
    Booking no3
    -----[----]---------------
    Booking no4
    -----------[---]----------
    Booking no5
    ------[-------]-----------
    Booking no6
    --------------[--------]--
    Booking no7
    -----[----------------]---
    

    You will have to find which periods cross over. Obviously cases 1 and 2 are free. Cases 3,5,6 are easy to catch as you can search if either the start date of the booking or the end date of the booking is within the user's selection. Cases 4 and 7 you would need to find if either of the user's selection dates would be between the bookings.

    So the following finds free rooms:

    DECLARE @ArrivalDate AS DATETIME
    DECLARE @DepartureDate AS DATETIME
    
    SELECT RoomType 
    FROM ROOMS 
    WHERE RoomID NOT IN 
    (
        SELECT RoomID 
        FROM   BOOKING B
               JOIN ROOMS_BOOKED RB
                   ON B.BookingID = RB.BookingID
        WHERE  (ArrivalDate <= @ArrivalDate AND DepartureDate >= @ArrivalDate) -- cases 3,5,7
               OR (ArrivalDate < @DepartureDate AND DepartureDate >= @DepartureDate ) --cases 6,6
               OR (@ArrivalDate <= ArrivalDate AND @DepartureDate >= ArrivalDate) --case 4
    )
    

提交回复
热议问题