PostgreSQL为所有用户获取最新的行/事件

Sam*_*rma 8 sql join greatest-n-per-group amazon-redshift

使用PostgreSQL 8.x(AWS Redshift)

我有这样的数据库结构:

userId: varchar, tstamp: datetime, event: string
Run Code Online (Sandbox Code Playgroud)

所以我要说我有以下几行

u2, t1, e1

u1, t2, e2

u2, t3, e1

u1, t4, e2
Run Code Online (Sandbox Code Playgroud)

其中u1和u2是用户ID,t [1..4]是时间戳,其中t1> t2> t3> t4,e1和e2是事件类型.

那么如何获取所有用户执行的最新事件.所以查询的输出将是:

u2, t3, e1

u1, t4, e2
Run Code Online (Sandbox Code Playgroud)

试图理解使用:https: //en.wikipedia.org/wiki/Correlated_subqueryPostgreSQL选择给定ID的最新条目

但我猜马慢慢的脑子.无法得到它.

bee*_*jay 18

你可以用Postgres做到这一点DISTINCT ON:

select distinct on(userId) userId, tstamp, event
from events
order by userId, tstamp desc;
Run Code Online (Sandbox Code Playgroud)

对于Redshift,您可以从我以前的一个答案中获得此变体:

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
Run Code Online (Sandbox Code Playgroud)