1

想象一个交易表和一个以交易 ID 连接的 cds_coupon 表;附有结算日期和结算金额的息票表。需要查询的是下一张票券结算的金额和日期。

    select t.tradeId AS tradeId,
(
  select settlement_date from cds_coupon e 
  where t.tradeId=e.tradeId 
  and e.settlement_date = (select min(settlement_date) from cds_coupon ei where ei.tradeId = t.tradeId  and ei.settlement_date > sysdate )
)  AS settlement_date,
( 
  select settlement_amount from cds_coupon e 
  where t.tradeId=e.tradeId 
  and e.settlement_date = (select min(settlement_date) from cds_coupon ei where ei.tradeId = t.tradeId and ei.settlement_date > sysdate )
)  AS settlement_amount, 
   FROM Trade t

可以看出,两个级别的相同关联被执行了两次,只是为了获取不同的字段——一次获取结算日期,一次获取结算金额。因此问题 - 如何引用和重用相关子查询?

4

2 回答 2

0

使用 JOIN 而不是相关子查询:

select t.tradeId, e.settlement_date, e.settlement_amount
from Trade t
join (select ei.tradeId, ei.settlement_date, ei.settlement_amount
      from cds_coupon ei
      join (select tradeId, min(settlement_date) min_date
            from cds_coupon
            where settlement_date > sysdate
            group by tradeId) emin
      on ei.tradeId = e.tradeId and ei.settlement_date = min_date) e
on t.tradeId = e.tradeId

子查询是用于查找包含字段的最小值或最大值的行的标准习惯用法。

于 2013-05-14T16:53:55.120 回答
0

如果使用 SQL Server,您可以使用公用表表达式 (CTE)

;WITH SettlementDates ()
AS
(
    SELECT tradeId, MIN(settlement_date) as settlement_date
    FROM cds_coupon  
    WHERE settlement_date > sysdate
    GROUP BY tradeId
)

SELECT e.trade_id, e.settlement_date, e.settlement_amount
FROM cds_coupon e
JOIN SettlementDates sd 
    ON (e.trade_id = sd.trade_id)
   AND (e.settlement_date = sd.settlement_date)
于 2013-05-14T16:42:01.170 回答