SQL案例陈述(有条件)

时间:2016-08-23 01:44:12

标签: sql

这是我的CASE声明:

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,

我想要只显示1个条件......

例如:

如果计数> 1然后在两个日期之间显示

如果计数> 1和NOT BETWEEN日期然后仅在不等于上述条件时显示。

最后,如果上述两个条件都不等同,则为-1。

1 个答案:

答案 0 :(得分:0)

您目前的尝试已接近尾声。正确的语法是:

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

请使用此CASE声明:

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