Postgres select all columns but group by one column

前端 未结 2 1814
有刺的猬
有刺的猬 2021-01-31 11:43

I have a simple table with a unit_id oid, time timestamp, diag bytea. The primary key is a combination of both time and unit_id.

The idea behind this query is to get the

2条回答
  •  梦如初夏
    2021-01-31 12:32

    Any time you start thinking that you want a localized GROUP BY you should start thinking about window functions instead.

    I think you're after something like this:

    select unit_id, time, diag
    from (
        select unit_id, time, diag,
               rank() over (partition by unit_id order by time desc) as rank
        from diagnostics.unit_diag_history
    ) as dt
    where rank = 1
    

    You might want to add something to the ORDER BY to consistently break ties as well but that wouldn't alter the overall technique.

提交回复
热议问题