Dette besvarer den originale version af problemet.
Du ser ud til at ville sammenligne totaler efter at have aggregeret tabel 2 og 3. Jeg ved ikke hvad table1
er for. Det ser ikke ud til at gøre noget.
Så:
select *
from (select partner_id, sum(quantity) as sum_quantity
from (select tdsl.*,
row_number() over (partition by t2.partner_id order by order_date) as seqnum
from trip_delivery_sales_lines tdsl
) tdsl
where seqnum <= 2
group by tdsl.partner_id
) tdsl left join
(select cl.partner_id, count(*) as leaf_cnt
from coupon_leaf cl
group by cl.partner_id
) cl
on cl.partner_id = tdsl.partner_id
where leaf_cnt is null or sum_quantity > leaf_cnt