简体   繁体   中英

SQL Case Expression (Conditional)

This is my CASE Expression:

case when count(distinct fcia.UserKey) > 1 and dd.FullDate between @CalcDate and @DefaultDate 
            then count(distinct fcia.UserKey)
else case when count(distinct fcia.UserKey) > 1 and dd.FullDate not between @CalcDate and @DefaultDate 
            then 0
else -1
end
end as StudentCount,

I would like to only display 1 condition, for example:

If the count > 1 and between the two dates then display

If the count > 1 and NOT BETWEEN dates then ONLY display if not equal to the above condition.

Lastly, else -1 if both conditions above do not equate.

Your current attempt is close. The correct syntax is:

CASE WHEN (condition1) THEN ... WHEN (condition2) THEN ... ELSE ... END

So use this CASE statement:

CASE WHEN COUNT(DISTINCT fcia.UserKey) > 1 AND
          dd.FullDate BETWEEN @CalcDate AND @DefaultDate 
     THEN COUNT(DISTINCT fcia.UserKey)
     WHEN COUNT(DISTINCT fcia.UserKey) > 1 AND
          dd.FullDate NOT BETWEEN @CalcDate AND @DefaultDate 
     THEN 0
     ELSE -1
END AS StudentCount

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM