Ну вот такое.
Т.е. не последний контракт, а строго по цепочке оснований.
Не вникал подробно в ситуацию, когда в основании прихода несколько заказов или в основании заказа несколько соглашений о поставке, поставил примитивный отбор по совпадению артикулов.
Статусы документов не проверяются.
Код:
SELECT t2.wo_id, t2.article, t2.wi_id, t2.or_id, t2.cq_id,
(SELECT d_cq.docco
FROM supermag.svdocnopricecq d_cq
WHERE d_cq.doctype = 'CQ' AND d_cq.id = t2.cq_id
) co_id
FROM (
SELECT t1.wo_id, t1.article, t1.wi_id, t1.or_id,
(SELECT MIN(b_cq.baseid) KEEP (DENSE_RANK FIRST ORDER BY s_cq.article ASC NULLS LAST)
FROM supermag.smcommonbases b_cq, supermag.smspec s_cq
WHERE b_cq.doctype = 'OR' AND b_cq.id = t1.or_id AND b_cq.basedoctype = 'CQ'
AND s_cq.doctype(+) = b_cq.basedoctype AND s_cq.docid(+) = b_cq.baseid AND s_cq.article(+) = t1.article
) cq_id
FROM (
SELECT s.docid wo_id, s.article, s.causeid wi_id,
(SELECT MIN(b_or.baseid) KEEP (DENSE_RANK FIRST ORDER BY s_or.article ASC NULLS LAST) or_id
FROM supermag.smcommonbases b_or, supermag.smspec s_or
WHERE b_or.doctype = s.causetype AND b_or.id = s.causeid AND b_or.basedoctype = 'OR'
AND s_or.doctype(+) = b_or.basedoctype AND s_or.docid(+) = b_or.baseid AND s_or.article(+) = s.article
) or_id
FROM supermag.smdocuments d, supermag.smspec s
WHERE s.doctype = 'WO'
AND d.opcode = 2
AND d.docstate = 3
AND d.locationfrom = :P_LOC
AND d.createdat BETWEEN :P_DATEFROM AND :P_DATETO
AND s.docid=d.id AND s.doctype=d.doctype
) t1
) t2
;