Question : SQL COUNT DISTINCT problem

I am using COUNT DISTINCT in a SQL "pivot table" but the numbers are not coming out right.  I am not getting any errors, but it seems to be adding 1 unit to some of the calculations.  It may be that I am not using COUNT DISTINCT correctly, or that I should not be using DISTINCT at all.

Line 13 calculates fine, but 15, 17, and 19 are not counting correctly.

Can anyone clue me in?

Thanks - Hubbs
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
DECLARE @strLASTEOM AS VARCHAR(10)
DECLARE @LASTEOM AS DATETIME
SET @strLASTEOM = '2/28/2010'
SET @LASTEOM = CAST(@strLASTEOM AS DATETIME)

SELECT AS_OF_DT
, SUM(CASE STATUS WHEN 'CURRENT' THEN UPB ELSE 0 END) AS [CURRENT]
, SUM(CASE STATUS WHEN '30 DPD' THEN UPB ELSE 0 END) AS [30 DPD]
, SUM(CASE STATUS WHEN '60 DPD' THEN UPB ELSE 0 END) AS [60 DPD]
, SUM(CASE STATUS WHEN '90 DPD' THEN UPB ELSE 0 END) AS [90 DPD]
, SUM(CASE STATUS WHEN 'FC' THEN UPB ELSE 0 END) AS [FC]
, (SUM(UPB)- SUM(CASE STATUS WHEN 'REO' THEN UPB ELSE 0 END)- SUM(CASE STATUS WHEN 'CLOSED' THEN UPB ELSE 0 END))AS [PORTFOLIO_UPB]
, COUNT(DISTINCT VCC_LnNum) AS [Portfolio_Units]
, SUM(CASE STATUS WHEN 'REO' THEN UPB ELSE 0 END) AS [REO_UPB]
, COUNT(DISTINCT CASE WHEN STATUS = 'REO' THEN UPB ELSE 0 END) AS [REO_Units]
, SUM(CASE STATUS WHEN 'REO-SOLD' THEN UPB ELSE 0 END) AS [REO-SOLD_UPB]
, COUNT(DISTINCT CASE STATUS WHEN 'REO-SOLD' THEN AS_OF_DT ELSE 0 END) AS [REO-SOLD_Units]
, SUM(CASE BK_ACTIVE WHEN 'ACTIVE' THEN UPB ELSE 0 END) AS [BK_UPB]
, COUNT(DISTINCT CASE BK_ACTIVE WHEN 'ACTIVE' THEN UPB ELSE 0 END) AS [BK_Units]


FROM EOM_VCCPORT3_wMOD
WHERE((AS_OF_DT <= @LASTEOM AND AS_OF_DT >= DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,@LASTEOM)-4,0))) OR
	           (AS_OF_DT = DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,@LASTEOM)-11,0))))
	 AND (STATUS <> 'CLOSED')
	 AND (FICO BETWEEN 0 AND 10000)
	 AND (Prop_Type Like '%')
	 AND (Prop_St Like '%')
	 AND (Occ_Status Like '%')
	 AND ((MOD_NOW Like '%') Or (MOD_NOW IS NULL))
	 AND (VCC_LTV_Orig BETWEEN 1 AND 100)   
	 
GROUP BY AS_OF_DT
ORDER BY AS_OF_DT DESC

Answer : SQL COUNT DISTINCT problem

The problem is that for SUM, you can use ELSE 0, because 0 adds nothing to the SUM.
For COUNT, or COUNT DISTINCT - do not use ELSE 0.  "0" itself is counted as one item.

, COUNT(DISTINCT CASE WHEN STATUS = 'REO' THEN UPB END) AS [REO_Units]
, SUM(CASE STATUS WHEN 'REO-SOLD' THEN UPB END) AS [REO-SOLD_UPB]
, COUNT(DISTINCT CASE STATUS WHEN 'REO-SOLD' THEN AS_OF_DT END) AS [REO-SOLD_Units]
, SUM(CASE BK_ACTIVE WHEN 'ACTIVE' THEN UPB END) AS [BK_UPB]
, COUNT(DISTINCT CASE BK_ACTIVE WHEN 'ACTIVE' THEN UPB END) AS [BK_Units]

In fact, you don't even need 0 for SUM.  SUM and COUNT both skip over NULL values.
Random Solutions  
 
programming4us programming4us