具有多个条件的案例陈述

时间:2015-11-13 10:03:35

标签: sql sql-server

我需要根据访问的天数从表中提取记录。如何通过更正下面的查询来实现这一目标?它有语法错误。我知道语法不正确,但它会让你知道我想要实现的目标。

DECLARE @PatientByDate INT
 SET @PatientByDate  = 30
    SELECT * FROM Visits
     WHERE
    CASE  
           WHEN(@PatientByDate = 90) then DaysVisited > 90
           WHEN(@PatientByDate = 60) then DaysVisited >= 60 AND DaysVisited < 90
           WHEN(@PatientByDate = 30) then DaysVisited >= 30 AND DaysVisited < 60
           WHEN(@PatientByDate = 25) then DaysVisited < 30
           WHEN(@PatientByDate = 0) then -500 AND <= 5000000
      END

2 个答案:

答案 0 :(得分:3)

直接将谓词与or组合:

SELECT * FROM Visits
WHERE
    (@PatientByDate = 90 and DaysVisited > 90) or
    (@PatientByDate = 60 and DaysVisited >= 60 and DaysVisited < 90) or
    (@PatientByDate = 30 and DaysVisited >= 30 and DaysVisited < 60) or
    (@PatientByDate = 25 and DaysVisited < 30) or
    (@PatientByDate in(0, -500))

答案 1 :(得分:0)

您必须将它们全部移动到 When 子句并将其与返回值(= 1)匹配:

DECLARE @PatientByDate INT
SET @PatientByDate  = 30
SELECT * FROM Visits
WHERE 1 = CASE  
    WHEN(@PatientByDate = 90) AND DaysVisited > 90 then 1 
    WHEN(@PatientByDate = 60) AND DaysVisited >= 60 AND DaysVisited < 90 then 1 
    WHEN(@PatientByDate = 30) AND DaysVisited >= 30 AND DaysVisited < 60 then 1 
    WHEN(@PatientByDate = 25) AND DaysVisited < 30 then 1 
    WHEN(@PatientByDate = 0) AND -500 AND <= 5000000 then 1 
END

或者干脆做:

DECLARE @PatientByDate INT
SET @PatientByDate  = 30
SELECT * FROM Visits
WHERE 
    ((@PatientByDate = 90) AND DaysVisited > 90) OR 
    ((@PatientByDate = 60) AND DaysVisited >= 60 AND DaysVisited < 90) OR 
    ((@PatientByDate = 30) AND DaysVisited >= 30 AND DaysVisited < 60) OR
    ((@PatientByDate = 25) AND DaysVisited < 30) OR
    ((@PatientByDate = 0) AND -500 AND <= 5000000)