Dette stykke kode fra forfatteren af SQLAlchemy i denne e-mailtråd kan være til hjælp
q1 =s.query(distinct(Appl.refid), Appl).\ filter(Appl.lastname.ilike('Williamson%')).\ filter(Appl.firstname.ilike('d% ')).\ group_by(Appl).\ order_by(Appl.refid, Appl.appldate.desc()) q1 =q1.cte('distinct_query') q2 =s.query(q1).order_by(q1.c. efternavn, q1.c.fornavn) q2.all()
udsender som:
MED distinct_query AS (SELECT DISTINCT appl.refid AS anon_1, appl.id AS id, appl.firstname AS fornavn, appl.lastname AS efternavn, appl.refid AS refid, appl.appldate AS appldate FRA appl WHERE appl.efternavn ILIKE %(efternavn_1)s OG appl.fornavn ILIKE %(fornavn_1)s GRUPPER EFTER appl.id, appl.firstname, appl.efternavn, appl.refid, appl.appldate BESTIL EFTER appl.refid, appl.appldate DESC ) SELECT distinct_query.anon_1 AS distinct_query_anon_1, distinct_query.id AS distinct_query_id, distinct_query.firstname AS distinct_query_firstname, distinct_query.lastname AS distinct_query_lastname, distinct_query.refid AS distinct_query_refid, distinct_query.appldate AS distinct_query_appldate FROM distinct_query ORDER BY distinct_query.lastname, distinct_query.firstname