SQL query to search for room availability

前端 未结 4 1599
你的背包
你的背包 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条回答
  • 2020-12-05 17:36

    this query list all rooms and for each room shows if it is available within [Arrival , Departure] dates

    SELECT 
        RoomType,
        case when NOT EXISTS (SELECT RoomID 
                      FROM ROOMS_BOOKED rb 
                      JOIN BOOKING b on b.BookingID = rb.BookingID
                      WHERE rb.RoomID = r.Id 
                        and ArrivalDate < 'param Departure Date here'
                        and DepartureDate > 'param Arrival Date here')
            then 1 else 0 end IsAvailable
    FROM ROOMS r
    
    0 讨论(0)
  • 2020-12-05 17:39

    here is a sample query which i used for checking the rooms which are not available, the query will return the unavailable rooms

    SELECT roomno FROM tbl_ReservedRooms WHERE ((fromdate BETWEEN @checkindate AND @checkoutdate )
    OR (todate BETWEEN @checkindate AND @checkoutdate)) 
    AND status = 'Active'
    
    0 讨论(0)
  • 2020-12-05 17:51

    SELECT * FROM room rm WHERE rm.Room_id NOT IN (SELECT DISTINCT Room_id FROM booking bk WHERE (bk.arrive_date BETWEEN '$from_date' AND '$to_date') OR (bk.departure_date BETWEEN '$from_date' AND '$to_date') OR (bk.arrive_date<'$from_date' AND bk.departure_date>'$to_date'))

    0 讨论(0)
  • 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
    )
    
    0 讨论(0)
提交回复
热议问题