Question : SQL - CASE Statement help needed

I am getting a Cout of Visits = 0 against a clients database when it should equal 3. When I run my sub select query in the Count of Visits by itself, I get a count of 3, however when its run the CASE statement, its giving me 0. I am confused were I messed up the SQL. Any insight is appreciated.
Code Snippet:
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:
35:
SELECT
        CASE 
                WHEN SUM(pva.PatBalance) + SUM(pva.InsBalance) > 1 THEN 
		(
		SELECT 
			COUNT(pv.PatientVisitId) 
		FROM
			PatientVisit pv
			JOIN PatientVisitAgg pva ON pva.PatientVisitId = pv.PatientVisitId
			JOIN Medlists bs ON pv.BillStatus = bs.JoinId
		WHERE
			bs.Code = 2 AND
			bs.TableName = 'BillStatus'
			and pva.PatBalance + pva.InsBalance > 1
		)
                ELSE 0
        END AS [Count of Visits],
        ISNULL(SUM(CASE WHEN (pva.InsBalance + pva.PatBalance > 1) THEN pva.InsBalance
                        ELSE 0
                        END) , 0)AS [Insurance Balance] ,
        ISNULL(SUM(CASE WHEN (pva.PatBalance + pva.InsBalance > 1) THEN pva.PatBalance
                        ELSE 0
                        END) , 0)AS [Patient Balance] ,
        bs.Code,
        bs.Description
FROM
        dbo.MedLists bs 
        LEFT JOIN dbo.PatientVisit pv ON pv.BillStatus = bs.JoinId 
        LEFT JOIN dbo.PatientVisitAgg pva ON pva.PatientVisitId = pv.PatientVisitId
WHERE
        bs.Code IN ( 2 ) AND
        bs.TableName = 'BillStatus'  -- Limit to BillStatus only
GROUP BY
        bs.code,
        bs.Description

Answer : SQL - CASE Statement help needed

try this

SELECT
      Sum ( CASE  WHEN pva.PatBalance + pva.InsBalance > 1 THEN  
1 ELSE 0 END) AS [Count of Visits],
        ISNULL(SUM(CASE WHEN (pva.InsBalance + pva.PatBalance > 1) THEN pva.InsBalance
                        ELSE 0
                        END) , 0)AS [Insurance Balance] ,
        ISNULL(SUM(CASE WHEN (pva.PatBalance + pva.InsBalance > 1) THEN pva.PatBalance
                        ELSE 0
                        END) , 0)AS [Patient Balance] ,
        bs.Code,
        bs.Description
FROM
        dbo.MedLists bs  
        LEFT JOIN dbo.PatientVisit pv ON pv.BillStatus = bs.JoinId  
        LEFT JOIN dbo.PatientVisitAgg pva ON pva.PatientVisitId = pv.PatientVisitId
WHERE
        bs.Code IN ( 2 ) AND
        bs.TableName = 'BillStatus'  -- Limit to BillStatus only
GROUP BY
        bs.code,
        bs.Description
Random Solutions  
 
programming4us programming4us