Skip to content

Instantly share code, notes, and snippets.

@inklesspen
Created July 25, 2015 14:29
Show Gist options
  • Save inklesspen/78687f14c4ff812a380f to your computer and use it in GitHub Desktop.
Save inklesspen/78687f14c4ff812a380f to your computer and use it in GitHub Desktop.
group by approach
latest_query = session.query(Certificate.csr_id, sqlalchemy.func.max(Certificate.not_after).label('not_after'))\
.group_by(Certificate.csr_id).subquery('latest')
session.query(Certificate.csr_id, Certificate.not_before, Certificate.not_after)\
.join(latest_query, sqlalchemy.and_(Certificate.csr_id == latest_query.csr_id, Certificate.not_after == latest_query.not_after))
SELECT csr_id, not_before, not_after FROM certificate
JOIN (SELECT csr_id, max(not_after) AS not_after FROM certificate GROUP BY csr_id) as latest
ON certificate.csr_id = latest.csr_id AND certificate.not_after = latest.not_after;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment