依靠sql中Case语句的结果

时间:2014-01-06 15:19:27

标签: sql sql-server tsql

嗨,当我在上面和下面交换case语句行时,我得到一个不同的值。哪个不好。有些人可以帮助我吗

SELECT
    CASE 
     WHEN dDate > '20130509' ANd dDate < '20130909' THEN 1
     WHEN dDate > '20130609' ANd dDate < '20131109' THEN 2
     WHEN dDate > '20130709' ANd dDate < '20131009' THEN 3 as DateVal,
CASE 
     WHEN dDate > '20130509' ANd dDate < '20130909' THEN COUNT(Encounter)
     WHEN dDate > '20130609' ANd dDate < '20131109' THEN COUNT(Encounter)
     WHEN dDate > '20130709' ANd dDate < '20131009' THEN COUNT(Encounter)) as Value
FROM Table 1

上述查询的结果是

 EncounterCount     Date
 230                 1
 45                  2
 20                  3

当稍微改变上面的查询时

SELECT
        CASE 
         WHEN dDate > '20130609' ANd dDate < '20131109' THEN 2
         **WHEN dDate > '20130509' ANd dDate < '20130909' THEN 1**
         WHEN dDate > '20130709' ANd dDate < '20131009' THEN 3 as DateVal,
    CASE 
         WHEN dDate > '20130609' ANd dDate < '20131109' THEN COUNT(Encounter)
         **WHEN dDate > '20130509' ANd dDate < '20130909' THEN COUNT(Encounter)**
         WHEN dDate > '20130709' ANd dDate < '20131009' THEN COUNT(Encounter)) as Value
    FROM Table 1

结果如下: 上述查询的结果是

 EncounterCount     Date
 45                 1
 150                2
 20                 3

这对我来说很奇怪。任何人都可以提供帮助。

1 个答案:

答案 0 :(得分:4)

那是因为您在WHEN子句中指定的日期间隔重叠。当CASE语句找到匹配的WHEN子句时,它将获得结果形式的子句并跳过其他子句。

您的某些记录可以匹配多个WHEN子句。重新排序子句时,可以更改行与另一个WHEN子句匹配的可能性。