select 1 as SOURCETYPE, PURCHASEINVOICE.ITSID as SOURCEID, PURCHASEINVOICE.ITSDATE as ITSDATE,
'AccPayable' as ACCDEBIT, 2004 as SUBACCDEBITTYPE, DEBTORCREDITOR.ITSID as SUBACCDEBITID, DEBTORCREDITOR.ITSNAME as SUBACCDEBIT, 
case when PURCHASEINVOICE.ITSTOTAL < PREPAYMENTTO.ITSTOTAL then PURCHASEINVOICE.ITSTOTAL else PREPAYMENTTO.ITSTOTAL end as DEBIT,
'PrepaymentsTo' as ACCCREDIT, 2004 as SUBACCCREDITTYPE, DEBTORCREDITOR.ITSID as SUBACCCREDITID, DEBTORCREDITOR.ITSNAME as SUBACCCREDIT,
case when PURCHASEINVOICE.ITSTOTAL < PREPAYMENTTO.ITSTOTAL then PURCHASEINVOICE.ITSTOTAL else PREPAYMENTTO.ITSTOTAL end as CREDIT
from PREPAYMENTTO
join PURCHASEINVOICE on PREPAYMENTTO.ITSID = PURCHASEINVOICE.PREPAYMENTTO
join DEBTORCREDITOR on DEBTORCREDITOR.ITSID = PURCHASEINVOICE.VENDOR
where PREPAYMENTTO.REVERSEDID is null and PURCHASEINVOICE.REVERSEDID is null and PURCHASEINVOICE.HASMADEACCENTRIES = 0 :WHEREADD
