It was not until I took this query off a demo db and plugged it into a live db that I found this issue. In fact, I didn't even think about it until I tried the query on a live db.
Here is my issue, The [NumberOfVisits] respects visits within specific dateranges, however my Sum on the InsBalance and PatBalance are not ( a complete oversight).
I need help on these two fields:
If you look at my full query below, in the [NumberofVisits] for bs.Code = '2' I want the query to only count the visit if it goes over 3 days. Well I need that same logic applied to the InsBalance and PatBalance fields. I only need the sum of money for the visits over "X" number of days. I need it to follow the same logic as my [NumberofVisits].
My full query:
Here is my issue, The [NumberOfVisits] respects visits within specific dateranges, however my Sum on the InsBalance and PatBalance are not ( a complete oversight).
I need help on these two fields:
Code:
ISNULL(SUM(pva.InsBalance) , 0) AS InsBalance,
ISNULL(SUM(pva.PatBalance) , 0) AS PatBalance,
If you look at my full query below, in the [NumberofVisits] for bs.Code = '2' I want the query to only count the visit if it goes over 3 days. Well I need that same logic applied to the InsBalance and PatBalance fields. I only need the sum of money for the visits over "X" number of days. I need it to follow the same logic as my [NumberofVisits].
My full query:
Code:
-- In Progress, Approve Failed, Approved, Batched, Hold, Filed Rejected, Sent, Filed Succeeded & Filed Statuses
SELECT
SUM(CASE WHEN ( bs.Code IN ( 2 , 4 , 5 , 16 ) ) AND
DATEDIFF(day , pv.lastmodified , GETDATE()) > 3 THEN 1
WHEN ( bs.Code IN ( 3 , 8 , 17 ) ) AND
DATEDIFF(day , pv.lastmodified , GETDATE()) > 10 THEN 1
WHEN ( bs.Code = 9 ) AND
DATEDIFF(day , pv.lastmodified , GETDATE()) > 30 THEN 1
WHEN ( bs.Code = 7 ) AND
DATEDIFF(day , pv.lastmodified , GETDATE()) > 45 THEN 1
ELSE 0
END) AS NumberOfVisits,
ISNULL(SUM(pva.InsBalance) , 0) AS InsBalance,
ISNULL(SUM(pva.PatBalance) , 0) AS PatBalance,
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 NOT IN ( 1 , 6 , 10 , 11 , 12 , 13 , 14 , 15 ) AND
bs.TableName = 'BillStatus' -- Limit to BillStatus only
GROUP BY
bs.code,
bs.Description