嵌套“CASE when”语句

时间:2012-05-15 22:58:41

标签: sql sql-server-2008

如何在sql查询中使用'case'语句的嵌套形式。我正在尝试执行以下查询。

SELECT AccessTabF1.Month, AccessTabF1.Year, AccessTabF1.[Entity Number], 
case when [Exp Year]= 2010 + 1
     then 'Expires in 1 to 5 Years'
     else
          case when [Exp Year]>2010 + 5
               then 'Expires After 5 Years'
               else 'No Expiration Year Listed' 
end
from AccessTabF1

1 个答案:

答案 0 :(得分:12)

在您的情况下,您不需要嵌套多个CASE表达式。

SELECT AccessTabF1.Month, AccessTabF1.Year, AccessTabF1.[Entity Number], 
case when [Exp Year] = 2010 + 1 -- why not = 2011 ?
     then 'Expires in 1 to 5 Years' -- this does not match the logic on line above
     when [Exp Year] > 2010 + 5 -- why not > 2015 ?
     then 'Expires After 5 Years'
     else 'No Expiration Year Listed' 
end
from AccessTabF1