SQL query to return first row from groupby query

July 25, 2022

SELECT x.object, x.metric, x.date, x.value
FROM data x
JOIN (
  SELECT p.object, p.metric, MAX(p.date) AS max_date
  FROM data p
  GROUP BY p.object, p.metric
) y
ON
  y.object = x.object
  AND y.metric = x.metric
  AND y.max_date = x.date
ORDER BY x.object, x.date desc
query_entities = [...]
query_filters = [...]
 
inner_stmt = select(
    [
        TableName,
        func.row_number()
        .over(
            partition_by=[TableName.object, TableName.metric],
            order_by=desc(TableName.date),
        )
        .label("row_num"),
    ]
).filter(*query_filters)
 
subq = inner_stmt.subquery()
 
stmt = (
    select(*query_entities)
    .join(subq, TableName.id == subq.c.id)
    .where(subq.c.row_num == 1)
)
 
response = session.execute(statement=stmt)