1

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

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

You can use CTE's for this. Something like this should work:

WITH cte_max_value AS (
SELECT 
  career_id, 
  uid, 
  max("time") as max_time
FROM mytable
GROUP BY career_id, uid
)
SELECT DISTINCT t.* 
FROM mytable AS t
INNER JOIN cte_max_value AS cmv 
  ON t.uid = cmv.uid AND t.career_id = cmv.career_id AND t.time = cmv.max_time

The CTE gives you all the unique combinations of career_id and uid with the relevant maximum time, the inner join then joins the entire rows into this. I'm using if you get two rows with the same maximum time for the same combination of career_id and uid you will get two rows returned. If you don't want that you will need to find a strategy to resolve this.

Edit: Also the proposed solution by a_hrose_with_name's solution is far nicer and unless you need some level of compatibility with other servers (sadly syntax varies) you should use that instead.

2 Comments

Those dreaded backticks are invalid in standard SQL and Postgres.
Thank you for pointing this out. Also, I definitely prefer your solution which is far more elegant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.