【问题标题】:Case statement with more than one condition具有多个条件的 case 语句
【发布时间】:2015-11-13 18:27:15
【问题描述】:

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

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

【问题讨论】:

标签: sql sql-server


【解决方案1】:

直接将谓词与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))

【讨论】:

    【解决方案2】:

    您必须将它们全部移至 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)
    

    【讨论】:

      猜你喜欢
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多