(select sum(writeoffamount) from #Request.prefix_db_agency#.Payments where invoice_id = p.invoice_id) as wOff,
p.PayerBalance,
pa.Patient_ID, pa.Last_Name_M0040,
a.Certification_Start,a.Certification_End, pa.First_Name_M0040, pa.Status,
DATE_FORMAT(pa.DOB_M0066,'%m/%d/%Y') AS DateOfBirth,
p.Invoice_Id,
DATE_FORMAT(p.DateSent,'%Y-%m-%d') AS DateSent,
DATE_FORMAT(s.PaymentDate,'%Y-%m-%d') AS PaymentDate,
DATE_FORMAT(p.DateSent,'%m/%d') AS ds,
(p.InvoiceTotal) as InvoiceTotal,
si.Total_EClaim,si.EClaimed_Final, si.Output_Type, p.PayerBalance,
pr.Payer_Id, pr.PayName, pr.Payer_Number,
(SELECT Invoice_Id FROM #Request.prefix_db_agency#.Invoices WHERE Assessment_Tracker_Id = p.Assessment_Tracker_Id
AND InvoiceTotal = '0.00' and Deleted <> 1 LIMIT 1) AS FinalBilling
from
#Request.prefix_db_agency#.Payments s left outer join #Request.prefix_db_agency#.ScheduleItems si on s.Invoice_ID = si.Invoice_ID
left outer join #Request.prefix_db_agency#.Invoices p on p.Invoice_ID = si.Invoice_ID
left outer join #Request.prefix_db_agency#.patient pa on pa.patient_id = p.patient_id
left outer join #Request.prefix_db_agency#.Payer pr on pr.payer_id = p.patientpayer_id
left outer join #Request.prefix_db_agency#.Assessment_New a on si.Assessment_ID = a.Assessment_ID
WHERE
p.Agency_Id = '#session.agencyid#'
AND p.Deleted IS NULL OR p.Deleted = 0