Skip to content
Advertisement

How to exclude a specific row from an SQL Count

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 GuestIDs. 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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement