I need to exclude a certain row from a COUNT
in SQL Server. This is what I have:
SELECT COUNT(GuestId)TotalBooked FROM GuestStayDetails WHERE (@ArrivalDate = ArrivalDate) OR (@DepartureDate = DepartureDate) OR (@ArrivalDate < ArrivalDate AND @DepartureDate = DepartureDate) OR (@ArrivalDate = ArrivalDate AND @DepartureDate < DepartureDate) OR (@ArrivalDate < ArrivalDate AND @DepartureDate > DepartureDate) OR (@ArrivalDate < DepartureDate AND @DepartureDate > DepartureDate) OR (@ArrivalDate BETWEEN ArrivalDate AND DATEADD(Day, -1, DepartureDate)) OR (@DepartureDate BETWEEN DATEADD(Day, -1, ArrivalDate) AND DepartureDate) AND Student = 1 AND Cancelled = 0 AND GuestStayDetails.GuestId != @GuestId;
If I remove the last AND GuestStayDetails.GuestId != @GuestId;
it gives me the expected COUNT
however I must exclude one of the GuestID
s. Any suggestions?
Advertisement
Answer
It looks like you are looking for overlapping time intervals — as well as your parentheses problem. If that is the case, you can significantly simplify the query:
WHERE @ArrivalDate <= DepartureDate AND @DepartureDate >= ArrivalDate AND Student = 1 AND Cancelled = 0 AND GuestStayDetails.GuestId <> @GuestId
This eliminates the need for any parentheses at all.