简体   繁体   中英

How can I write this SQL query in SQLAlchemy?

I wrote the following SQL query. How can I do the same thing in SQLAlchemy?

SELECT
    T.campaign_id,
    T.spend,
    T.id
FROM activity_log T
WHERE T.end_time = (
    SELECT MAX( T1.end_time ) FROM activity_log T1
    WHERE T1.campaign_id = T.campaign_id and cast(T1.end_time as DATE) = cast(T.end_time as DATE)
);

Below should get you started:

T = aliased(ActivityLog, name="T")
T1 = aliased(ActivityLog, name="T1")
subquery = (
    session.query(func.max(T1.end_time).label("end_time"))
    .filter(T1.campaign_id == T.campaign_id)
    .filter(cast(T1.end_time, Date) == cast(T.end_time, Date))
    .correlate(T)
    .as_scalar()
)

qry = (
    session.query(T.campaign_id, T.spend, T.id)
    .filter(T.end_time == subquery)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM