使用SELECT CASE语句时出现意外的NULL结果

时间:2015-07-13 18:30:00

标签: sql-server case aggregate-functions

以下是我的疑问:

DECLARE
    @ThisYear INT = CAST(DATEPART(yy, GETDATE()) AS INT) 
    ,@LastYear INT = CAST(DATEPART(yy, GETDATE()) - 1 AS INT)

SELECT
    CASE WHEN CAST(DATEPART(yy, mq.[qDate]) AS INT)   = @ThisYear THEN 5
            WHEN CAST(DATEPART(yy, mq.[qDate]) - 1 AS INT) = @LastYear THEN 6 END AS 'TimePeriodID'
    ,Name = 'QueryTotals'
    ,SUM(CASE WHEN dQuery = 1 THEN 1 ELSE 0 END) AS 'DefaultQuery'
    ,SUM(CASE WHEN dQuery = 0 THEN 1 ELSE 0 END) AS 'Non-DefaultQuery'
    ,COUNT(dQuery) AS 'TotalQueries'
FROM 
    mQuery mq
INNER JOIN 
    mParameter mp
    ON
    mq.id = mp.id
INNER JOIN 
    Variable v
    ON
    mp.id = v.id
WHERE 
    v.id <= 10
GROUP BY
    CASE WHEN CAST(DATEPART(yy, mq.[qDate]) AS INT)   = @ThisYear THEN 5
            WHEN CAST(DATEPART(yy, mq.[qDate]) - 1 AS INT) = @LastYear THEN 6 END

以下是我的搜索结果的屏幕截图:

enter image description here

请忽略TimePeriodID = 1, 2, 3, 4行,因为这些行UNION已显示在相关问题中。

为什么我应该在NULL时在TimePeriodID中获得6

请注意,结果总计是正确的,表格中的日期包含满足6条件的日期。

我对此感到茫然。

额外的眼睛会非常棒。

感谢。

1 个答案:

答案 0 :(得分:2)

这种陈述的组合:

DECLARE
    @ThisYear INT = CAST(DATEPART(yy, GETDATE()) AS INT) 
    ,@LastYear INT = CAST(DATEPART(yy, GETDATE()) - 1 AS INT)

SELECT
    CASE WHEN CAST(DATEPART(yy, mq.[qDate]) AS INT)   = @ThisYear THEN 5
            WHEN CAST(DATEPART(yy, mq.[qDate]) - 1 AS INT) = @LastYear THEN 6 END AS 'TimePeriodID'

使第二种情况永远不可能成真。如果第一次施放!= @ ThisYear,那么第二次施法(第一次 - 1次)不能== @LastYear,因为@LastYear = @ThisYear - 1.

这就是原因。解决方案尚不清楚,因为您没有显示您正在尝试做的事情。