select distinct apii.*
from ap_invoices_all api
left outer join ap_invoice_payments_all apip on (apip.invoice_id = api.invoice_id and
apip.set_of_books_id = api.set_of_books_id)
left outer join ap_checks_all apic on (apic.check_id = apip.check_id and
(apip.invoice_id = api.invoice_id and
apip.set_of_books_id = api.set_of_books_id))
left outer join hz_parties hzp on hzp.party_id = api.party_id
left outer join poz_supplier_sites_all_m pss on pss.vendor_site_id = api.vendor_site_id
left outer join poz_suppliers supp on supp.vendor_id = pss.vendor_id
left outer join poz_suppliers_pii psp on psp.vendor_id = supp.vendor_id
left outer join xle_entity_profiles xle_ep on xle_ep.legal_entity_id = api.legal_entity_id
left join ap_invoice_distributions_all ppd on ppd.invoice_id = api.invoice_id
left join ap_invoice_lines_all apl on (ppd.invoice_id = apl.invoice_id and ppd.INVOICE_LINE_NUMBER = apl.LINE_NUMBER)
left join ap_invoices_all apii on apii.invoice_id = apl.prepay_invoice_id
where 1 = 1
and api.set_of_books_id = 300000005623306
and api.approval_status != 'CANCELLED'
and api.invoice_currency_code != 'RUB'
and (apic.status_lookup_code != 'VOIDED' or apic.status_lookup_code is NULL)
and invoice_num like 'AGRACEP1002%'
/*PARAMETERS*/
--and api.legal_entity_id in (:p_legal_entity_id)
--order by xle_ep.name,
-- hzp.party_name,
-- api.invoice_date,
-- api.invoice_num
order by apl.invoice_id