简体   繁体   中英

How to perform date_trunc query in Postgres using SQLAlchemy

I can't seem to be able to translate the following query into SQLAlchemy.

I would like to translate the following query:

SELECT date_trunc('day', time), "PositionReport".callsign FROM tvh_aircraft."PositionReport" WHERE "PositionReport".reg = 'PH-BVA'
GROUP BY 1, "PositionReport".callsign

I've tried the following, but with no luck.

flight_days = session\
        .query(PositionReport)\
        .filter(PositionReport.reg == reg) \
        .group_by(func.date_trunc('day', PositionReport.time))\
        .group_by('1')\
        .all()

    trunc_date = func.date_trunc('day', PositionReport.time)
    flight_days = session.query(trunc_date, PositionReport.callsign) \
        .filter(PositionReport.reg == reg) \
        .group_by("date_trunc_1")

Thanks in advance for your help.

session.query(func.date_trunc('day', PositionReport.time), 
              PositionReport.callsign) \
    .filter(PositionReport.reg=='PH-BVA') \
    .group_by(func.date_trunc('day', PositionReport.time),
              PositionReport.callsign).all()

or if you need exactly GROUP BY 1

from sqlalchemy import text

session.query(func.date_trunc('day', PositionReport.time), 
              PositionReport.callsign) \
    .filter(PositionReport.reg=='PH-BVA') \
    .group_by(text('1'),
              PositionReport.callsign).all()

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