Search code examples
postgresqlgreatest-n-per-group

Postgres distinct query in two columns


I want to write a postgres query. For every distinct combination of (career-id and uid) I should return the entire row which has max time. This is the sample data

id  time    career_id   uid  content
1   100     10000        5     Abc
2   300      6           7     xyz
3   200     10000        5     wxv
4   150      6           7     hgr

Ans:

id  time    career_id   uid   content
2   300           6       7   xyz
3   200       10000       5   wxv

Solution

  • this can be done using distinct on () in Postgres

    select distinct on (career_id, uid) *
    from the_table
    order by career_id, uid, "time" desc;