Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL get latest rows/events for all users

Working on PostgreSQL 8.x (AWS Redshift)

I have a db structure like this:

userId: varchar, tstamp: datetime, event: string

So let's say I have the following rows

u2, t1, e1

u1, t2, e2

u2, t3, e1

u1, t4, e2

Where u1 and u2 are userids, t[1..4] are timestamps where t1>t2>t3>t4 and e1 and e2 are types of events.

So how do I get latest events performed by all users. So the output of the query would be:

u2, t3, e1

u1, t4, e2

Tried to understand using: https://en.wikipedia.org/wiki/Correlated_subquery and PostgreSQL Selecting Most Recent Entry for a Given ID

But I guess m a slow brain. Couldn't get it.

like image 543
Sambhav Sharma Avatar asked Jun 16 '15 13:06

Sambhav Sharma


Video Answer


1 Answers

You can do this with Postgres' DISTINCT ON:

select distinct on(userId) userId, tstamp, event
from events
order by userId, tstamp desc;

For Redshift, you might be able to this variant from one of my previous answers:

select userId, tstamp, event from (
  select userId, tstamp, event, 
  row_number() over (partition by userId order by tstamp desc) as rownumber 
  from events
) foo
where rownumber = 1
like image 186
beerbajay Avatar answered Sep 22 '22 15:09

beerbajay