组合条件字段格式的CASE表达式

时间:2016-12-14 20:02:58

标签: sql sql-server tsql sql-server-2012 case-when

尝试编写CASE表达式,我需要在组合中评估Family_sizeIncome,以便在任何组合为真时将Status AS设置为下方。

CASE
    ((WHEN Family_size = 1 AND Income <=11800)
      OR(WHEN Family_size = 2 AND Income <=16020)
      OR(WHEN Family_size = 3 AND Income <=20160)
      OR(WHEN Family_size = 4 AND Income <=24300)
      OR(WHEN Family_size = 5 AND Income <=28400)
      OR(WHEN Family_size = 6 AND Income <=32580)
      OR(WHEN Family_size = 7 AND Income <=36730)
      OR(WHEN Family_size = 8 AND Income <=40890)
     THEN 'Below' ELSE 'Above' END) AS [Status]

这给出了错误:

  

关键字'WHEN'

附近的语法不正确

有一个巧妙的技巧还是我必须单独写THEN 'Below'?像:

CASE
      WHEN Family_size = 1 AND Income <=11800 THEN 'Below'
      WHEN Family_size = 2 AND Income <=16020 THEN 'Below'
and so on...

3 个答案:

答案 0 :(得分:2)

尝试

SELECT CASE
    WHEN (Family_size = 1 AND Income <=11800)
      OR(Family_size = 2 AND Income <=16020)
      OR(Family_size = 3 AND Income <=20160)
      OR(Family_size = 4 AND Income <=24300)
      OR(Family_size = 5 AND Income <=28400)
      OR(Family_size = 6 AND Income <=32580)
      OR(Family_size = 7 AND Income <=36730)
      OR(Family_size = 8 AND Income <=40890)
     THEN 'Below' ELSE 'Above' END AS [Status]

答案 1 :(得分:2)

如上所述,请尝试:

 CASE WHEN (Family_size = 1 AND Income <=11800)
   OR (Family_size = 2 AND Income <=16020)
   OR (Family_size = 3 AND Income <=20160)
   OR (Family_size = 4 AND Income <=24300)
   OR (Family_size = 5 AND Income <=28400)
   OR (Family_size = 6 AND Income <=32580)
   OR (Family_size = 7 AND Income <=36730)
   OR (Family_size = 8 AND Income <=40890)
     THEN 'Below' ELSE 'Above' END AS [Status]

答案 2 :(得分:2)

根据 federal poverty guideline 2016 进行更正。

根据这些 poverty guidelines 进行额外更正,以包含大于8的家庭成员。

select [Status] =
  case
  when (Family_size = 1 and Income <=11880) -- Corrected to 11880 for federal poverty guideline 2016
     or(Family_size = 2 and Income <=16020)
     or(Family_size = 3 and Income <=20160)
     or(Family_size = 4 and Income <=24300)
     or(Family_size = 5 and Income <=28440) -- Corrected to 28440  for federal poverty guideline 2016
     or(Family_size = 6 and Income <=32580)
     or(Family_size = 7 and Income <=36730)
     or(Family_size = 8 and Income <=40890)
  then 'Below' else 'Above' end as 

可以改写为:

select [Status] = case
     when  Family_size < 7  and Income <= (11880 + ((family_size-1)*4140)) 
      then 'Below'
     when  Family_size >= 7 and Income <= (36730 + ((family_size-7)*4160)) 
      then 'Below'
      else 'Above' 
      end

要确认上述案例陈述中的方程是正确的,您可以检查此rextester链接,该链接使用相同的方程式生成1-12的贫困表: http://rextester.com/AWRCK1808 < / p>

您可能需要考虑到州,因为阿拉斯加州和夏威夷州的贫困人数不同。