Pergunta

I want to show all propID live today.

I have DateLive & DateRemoved for each propID on the PC table but some have a NULL DateRemoved (as they are still live).

I need to use an IF (CASE) statement in my WHEREe to do this.

Something like...

Where it's today, AND (IF they don't have a DateRemoved) then datelive < CalendarDate OR IF they do have a Date Removed then CalendarDate is Between DateLive and DateRemoved)

SELECT

C.CalendarDate,
PC.propID

FROM Calendar C
CROSS join PropertyCounts PC 

Where C.CalendarDate = getdate()

AND
(CASE
WHEN PC.DateRemoved <>NULL THEN C.CalendarDate BETWEEN PC.DateLive AND PC.Dateremoved
WHEN PC.DateRemoved = NULL THEN PC.DateLive < C.CalendarDate  )
Foi útil?

Solução

where C.CalendarDate = getdate()
    AND ((PC.DateRemoved is not null AND C.CalendarDate between PC.DateLive AND PC.Dateremoved)
         OR
         (PC.DateRemoved is null AND PC.DateLive < C.CalendarDate)
        )

You're already in an IF statement of sorts with the Where clause. You simply need to build the boolean logic that evaluates to TRUE when a particular record should be selected.

Outras dicas

Try to insert this on your where clause substituting the case in parenthesis:

... and ((pc.dateremoved IS NOT NULL and c.calendarDate between pc.datelive and pc.dateremoved) or (pc.dateremoved IS NULL and pc.datelive < c.calendardate))

You don't need the complexity of a CASE expression (or an IF statement), just boolean logic with AND and OR

Where C.CalendarDate = getdate()

AND
(
   (PC.DateRemoved IS NOT NULL AND
      C.CalendarDate BETWEEN PC.DateLive AND PC.Dateremoved)
    OR
   (PC.DateRemoved IS NULL AND PC.DateLive < C.CalendarDate)
)

You might also need to do some fiddling around to remove the time component from getdate(), e.g. your first condition might need to be:

Where C.CalendarDate = CONVERT(date,getdate())

because getdate() returns a datetime with both parts populated, not just a plain date with no time component.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top