我可能会因为询问而分崩离析,但为什么在比较两种不同场景中的Claims_Completed时,这些会产生不同的结果? Claims_Completed值与两种情况下的Claims_Received相同。
SELECT
DischargeType
,COUNT(CASE WHEN (DateReceived > '2/1/2015' AND DateReceived < DATEADD(dd, 1, '2/28/2015')) THEN 1 ELSE 0 END) AS Claims_Received
,COUNT(CASE WHEN (DateCompleted > '2/1/2015' AND DateCompleted < DATEADD(dd, 1, '2/28/2015')) THEN 1 ELSE 0 END) AS Claims_Completed
FROM Claims GROUP BY DischargeType
情景2:
SELECT COUNT(*) AS Claims_Received
FROM Claims
WHERE DateReceived > '2/1/2015' AND DateReceived < DATEADD(dd, 1, '2/28/2015')
GROUP BY DischargeType
SELECT COUNT(*) AS Claims_Completed
FROM Claims
WHERE DateCompleted > '2/1/2015' AND DateCompleted < DATEADD(dd, 1, '2/28/2015')
GROUP BY DischargeType
答案 0 :(得分:2)
您需要sum()
而不是count()
:
SELECT DischargeType,
SUM(CASE WHEN (DateReceived > '2/1/2015' AND
DateReceived < DATEADD(dd, 1, '2/28/2015'))
THEN 1 ELSE 0
END) AS Claims_Received,
SUM(CASE WHEN (DateCompleted > '2/1/2015' AND
DateCompleted < DATEADD(dd, 1, '2/28/2015'))
THEN 1 ELSE 0
END) AS Claims_Completed
FROM Claims
GROUP BY DischargeType;
因为count()
在这里误解,因为它会将0作为值或数据计算。
答案 1 :(得分:1)
COUNT
将计算序列中的所有非空值。由于1和0都是非null,因此它计算所有内容。一种选择是使用NULL而不是0:
SELECT
DischargeType
,COUNT(CASE WHEN (DateReceived > '2/1/2015'
AND DateReceived < DATEADD(dd, 1, '2/28/2015'))
THEN 1 ELSE NULL END) AS Claims_Received
,COUNT(CASE WHEN (DateCompleted > '2/1/2015'
AND DateCompleted < DATEADD(dd, 1, '2/28/2015'))
THEN 1 ELSE NULL END) AS Claims_Completed
FROM Claims
GROUP BY DischargeType