0

I need help.. I have a table below.. I need to get the entire row with minimum value for the datecreated column

  id      group    users       datecreated
  ===========================================
 *39583 | group1 | user1 | 7/6/2015 23:28
  39583 | group1 | user1 | 7/6/2015 23:37
  39583 | group1 | user2 | 7/7/2015 15:27
  39583 | group1 | user2 | 7/7/2015 19:39
  39583 | group1 | user3 | 7/7/2015 22:17
  39583 | group1 | user4 | 7/8/2015 19:18
  39583 | group1 | user3 | 7/9/2015 2:35
  39583 | group1 | user5 | 7/9/2015 14:19
 *39123 | group1 | user5 | 7/5/2015 14:19
  39123 | group1 | user1 | 7/5/2015 23:28
  39123 | group1 | user1 | 7/5/2015 23:37
  39123 | group1 | user2 | 7/5/2015 15:27
  39123 | group1 | user2 | 7/6/2015 19:39
  39123 | group1 | user3 | 7/6/2015 22:17
  39123 | group1 | user4 | 7/6/2015 19:18
  39123 | group1 | user3 | 7/7/2015 2:35
  39123 | group1 | user5 | 7/7/2015 14:19
  39123 | group1 | user5 | 7/7/2015 14:19

I want to get the following rows... in postgres

id    group    users       datecreated
===========================================
39583   | group1 | user1 | 7/6/2015 23:28
39123   | group1 | user5 | 7/5/2015 14:19
2
  • What logic did you use to get only those 2 rows? Why rows with user2..4 are excluded? Commented Sep 15, 2015 at 18:44
  • Need to get the first occurence per ID... Commented Sep 16, 2015 at 4:22

3 Answers 3

1

You can use row_number to get the desired result.

select id, group, users, datecreated from
(
select *, row_number() over(partition by id order by datecreated) as rn
from tablename
) t 
where t.rn = 1;
Sign up to request clarification or add additional context in comments.

Comments

0

You can do a GROUP BY and perform a JOIN with the main table like

select t.id,      
t.group,    
t.users,       
t.datecreated
from table1 t join (
select min(datecreated) as mindatecreated, id
from table1
group by id) xx 
on t.id = xx.id and t.datecreated = xx.mindatecreated;

Comments

0

Using Postgres' distinct on() is usually faster than a solution using window function (and both are usually faster than a solution with a sub-select)

select distinct on (id) id, "group", users, datecreated
from the_table
order by id, datecreated;

note that group is a reserved keyword and cannot be used as a column name without quoting.

Comments

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.