SELECT x1
y
z
e
f
Case When DATEDIFF(dd, CreateDate, GetDate()) >= 120 Then 1 Else 0 End As Over120Flag,
Sum(Units) As TtlUnits,
Sum(VisitCt) As TtlVisitCt,
Sum(Chgamt) As ChgCt,
Sum(TrnChgAmt) As ChgAmt,
Sum(TrnPayAmt) As PayAmt,
Sum(TrnChgAmt) - Sum(TrnPayAmt) - (Sum(TrnChgAmt) + Abs(Sum(TrnDebitAmt)) - Sum(TrnPayAmt) - Sum(TrnAdjAmt)- Sum(TrnCreditAmt) - Sum(TranCourtesyAmt)) As AdjAmt,
Sum(TrnAdjAmt) As ContAdjAmt,
Sum(TrnCreditAmt) As CredAmt,
Abs(Sum(TrnDebitAmt)) As DebitAmt,
Sum(TranCourtesyAmt) As CourtesyAmt,
Sum(TrnChgAmt) + Abs(Sum(TrnDebitAmt)) - Sum(TrnPayAmt) - Sum(TrnAdjAmt)- Sum(TrnCreditAmt) - Sum(TranCourtesyAmt) As OwedAmt,
INTO qqqy
FROM
(
SELECT x1,
y,
z,
l,
CASE WHEN PayCat = 'PAYMENTS' Then origTrnPayAmt - origTrnDebitAmt Else 0 End As TrnPayAmt,
TrnAdjAmt,
CASE WHEN PayCat = 'CREDITS' Then origTrnCreditAmt + origTrnPayAmt Else
CASE WHEN PayCat ='WRITE OFF' Then origTrnCreditAmt + origTrnPayAmt - origTrnDebitAmt Else 0 End
End As TrnCreditAmt,
CASE WHEN PayCat = 'DISCOUNTS' Then origTrnCreditAmt Else 0 End As TranCourtesyAmt,
CASE WHEN PayCat ='REFUNDS' Then origTrnPayAmt Else
CASE WHEN PayCat = 'DEBIT' Then origTrnDebitAmt Else 0 End End As TrnDebitAmt,
FROM kkkyz x
INNER JOIN
lllqf AS q WITH (NOLOCK)
ON x.x1 = q.x1
) s2
GROUP x1,y,z