select 2 as SOURCETYPE, SALESINVOICE.ITSID as SOURCEID, SALESINVOICE.ITSDATE as ITSDATE,
'PrepaymentsFrom' as ACCDEBIT, 2004 as SUBACCDEBITTYPE, DEBTORCREDITOR.ITSID as SUBACCDEBITID, DEBTORCREDITOR.ITSNAME as SUBACCDEBIT, 
case when SALESINVOICE.ITSTOTAL < PREPAYMENTFROM.ITSTOTAL then SALESINVOICE.ITSTOTAL else PREPAYMENTFROM.ITSTOTAL end as DEBIT,
'AccReceivable' as ACCCREDIT, 2004 as SUBACCCREDITTYPE, DEBTORCREDITOR.ITSID as SUBACCCREDITID, DEBTORCREDITOR.ITSNAME as SUBACCCREDIT,
case when SALESINVOICE.ITSTOTAL < PREPAYMENTFROM.ITSTOTAL then SALESINVOICE.ITSTOTAL else PREPAYMENTFROM.ITSTOTAL end as CREDIT
from PREPAYMENTFROM
join SALESINVOICE on PREPAYMENTFROM.ITSID = SALESINVOICE.PREPAYMENTFROM
join DEBTORCREDITOR on DEBTORCREDITOR.ITSID = SALESINVOICE.CUSTOMER
where PREPAYMENTFROM.REVERSEDID is null and SALESINVOICE.REVERSEDID is null and SALESINVOICE.HASMADEACCENTRIES = 0 :WHEREADD
