SQLAlchemy 中的外部应用

OUTER APPLY in SQLAlchemy

我想使用 SQLAlchemy 编写一个 SQL 服务器的外部应用查询,如下所示。

FX table 可能在价格 table 中没有日期对应的行,所以我需要使用 OUTER APPLY 来获取 FX [=37= 中的最后一行] 每个日期。

SELECT p.EffectiveDate, p.Close_ * FX.Rate as USD_PRICE
FROM PRICE p
OUTER APPLY (
    SELECT TOP 1 *
    FROM FX
    WHERE 
        FromCurrency = p.Currency
        AND ToCurrency = 'USD'
        AND ExRateDate <= p.EffectiveDate
    ORDER BY ExRateDate DESC
) fx

table 的简要背景:

似乎 SQLAlchemy 不支持外部应用表达式。我看了一下Custom SQL Constructs and Compilation Extension。但我不确定如何创建外部应用的自定义构造。你有这方面的例子吗?

我想一个解决方法是用外部连接替换外部应用。如果你能提供一个不使用外部应用也能产生相同结果的查询,那也能解决我的问题。

谢谢

使用Correlated Subquery这里是使用OUTER JOIN的解决方案:

sq = (
    session.query(FX.id.label("last_id"))
    .filter(FX.FromCurrency == Price.Currency)
    .filter(FX.ToCurrency == 'USD')
    .filter(FX.ExRateDate <= Price.EffectiveDate)
    .order_by(FX.ExRateDate.desc())
    .order_by(FX.id.desc())  # handle duplicates just in case
    .limit(1)
    .correlate(Price)
    .as_scalar()
)

q = session.query(
    Price.EffectiveDate,
    (Price.Close_ * FX.Rate).label("USD_PRICE"),
).outerjoin(FX, FX.id == sq)