Skip to content
Advertisement

First row of all groups in Flask SQLAlchemy

I want to group the database by gauge_id and then get the row having maximum time_col. This is my current code:

But I am only able to get both gauge_id and time_col. When I add another column (reading), like this:

it gives this error.

How do I return the top row of each groups? Thanks in advance.

Advertisement

Answer

One way to do this would be with a common table expression (CTE). The CTE creates a virtual table of the group by resultset which we can then join against.

The SQL would be

The SQLAlchemy equivalent would be

(the above example uses “pure” SQLAlchemy rather than Flask-SQLAlchemy – it should be enough to replace sa. with db. and session with db.session to get it working in Flask_SQLAlchemy)

It’s worth noting that CTEs were not handled efficiently in Postgresql until v12, so if you are on an earlier version it may be better to inline the CTE as a subquery.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement