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
|