correlated subquery - How to reference and reuse a corelated sub query? -
imagine trade table , cds_coupon table joined on trade id; coupon table having settlement date , settlement amount well. required query amount , date of next coupon settle.
select t.tradeid tradeid, ( select settlement_date cds_coupon e t.tradeid=e.tradeid , e.settlement_date = (select min(settlement_date) cds_coupon ei ei.tradeid = t.tradeid , ei.settlement_date > sysdate ) ) settlement_date, ( select settlement_amount cds_coupon e t.tradeid=e.tradeid , e.settlement_date = (select min(settlement_date) cds_coupon ei ei.tradeid = t.tradeid , ei.settlement_date > sysdate ) ) settlement_amount, trade t
as can seen 2 levels of identical corelation done twice grab different field - once grab settlement date , once grab settlement amount. hence question - how reference , reuse corelated sub query ?
if using sql server use common table expression (cte).
;with settlementdates () ( select tradeid, min(settlement_date) settlement_date cds_coupon settlement_date > sysdate group tradeid ) select e.trade_id, e.settlement_date, e.settlement_amount cds_coupon e join settlementdates sd on (e.trade_id = sd.trade_id) , (e.settlement_date = sd.settlement_date)
Comments
Post a Comment