理解“Where”子句中的case表达式

时间:2012-11-20 22:05:17

标签: sql sql-server

我在这里有这个代码,你可以从我的伪代码中看到我想要完成的事情

select *

from dbo.BenefitsForms
     inner join Dependents on BenefitsForms.UserId = Dependents.BenefitsForm_UserId
     inner join CoverageLevels on BenefitsForms.MedicalId = CoverageLevels.Id

where (BenefitsForms.MedicalId > 0 AND BenefitsForms.MedicalId < 13)
  AND Dependents.IsSpouse = CASE when CoverageLevels.[Level] = 2 then 1
                                 when CoverageLevels.[Level] = 3 then 0 end
                                 when CoverageLevels.[Level] = 4 then [any, it doesnt matter] <--- my desire but it doesn't work.

如何在括号中获得我想要的效果?如果Coverage Level = 4那么我不关心Dependents.IsSpouse是什么,我甚至不需要再按它排序了。

1 个答案:

答案 0 :(得分:7)

假设isSpouse只能01 ...如果CoverageLevels.Level4,则将isSpouse与自身进行比较,这将始终导致true

AND Dependents.IsSpouse = CASE 
    when CoverageLevels.[Level] = 2 then 1
    when CoverageLevels.[Level] = 3 then 0
    when CoverageLevels.[Level] = 4 then Dependents.IsSpouse
END

或者,也可以在没有CASE

的情况下表达
WHERE
    BenefitsForms.MedicalId > 0 
    AND BenefitsForms.MedicalId < 13
    AND (
        (Dependents.IsSpouse = 1 AND CoverageLevels.[Level] = 2)
        OR (Dependents.IsSpouse = 0 AND CoverageLevels.[Level] = 3)
        OR CoverageLevels.[Level] = 4
    )