Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlAlchemy group_by and return max date

I have a table such has

identifier date        value
A          2017-01-01  2 
A          2017-01-02  1
A          2017-01-03  7
B          2017-01-01  2 
B          2017-01-02  7
B          2017-01-03  3

I am trying to select the max date of each identifier such as I get :

identifier date        value
A          2017-01-03  7
B          2017-01-03  3

thank you

like image 313
Steven G Avatar asked Aug 19 '17 19:08

Steven G


3 Answers

Using a subquery:

SELECT t1.identifier, t1.date, t1.value FROM table t1
JOIN
(
    SELECT identifier, MAX(date) maxdate
    FROM table
    GROUP BY identifier
) t2
ON t1.identifier = t2.identifier AND t1.date = t2.maxdate;

In SQLAlchemy:

from sqlalchemy import func, and_

subq = session.query(
    Table.identifier,
    func.max(Table.date).label('maxdate')
).group_by(Table.identifier).subquery('t2')

query = session.query(Table).join(
    subq,
    and_(
        Table.identifier == subq.c.identifier,
        Table.date == subq.c.maxdate
    )
)
like image 85
r-m-n Avatar answered Oct 19 '22 23:10

r-m-n


With ORM you could use over function that is actually is a window function:

session \
    .query(Table, func.max(Table.date)
           .over(partition_by=Table.identifier, order_by=Table.value))

It returns a tuple (table_instance, latest_datetime). order_by is optional in this case.

The same with SQL Expressions.

like image 10
Eugene Lopatkin Avatar answered Oct 19 '22 23:10

Eugene Lopatkin


In SQLAlchemy core, it can be achieved using the following code -

import sqlalchemy as db

query = db.select([
    TABLE.c.identifier,
    db.func.max(USERS.c.date),
    TABLE.c.value,
]).group_by(TABLE.c.identifier)

result = engine.execute(query).fetchall()
like image 2
Amit Pathak Avatar answered Oct 19 '22 22:10

Amit Pathak