【问题标题】:PostgreSQL get latest rows/events for all usersPostgreSQL 获取所有用户的最新行/事件
【发布时间】:2015-09-01 07:51:41
【问题描述】:

使用 PostgreSQL 8.x (AWS Redshift)

我有一个这样的数据库结构:

userId: varchar, tstamp: datetime, event: string

假设我有以下行

u2, t1, e1

u1, t2, e2

u2, t3, e1

u1, t4, e2

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

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

u2, t3, e1

u1, t4, e2

试图理解使用: https://en.wikipedia.org/wiki/Correlated_subqueryPostgreSQL Selecting Most Recent Entry for a Given ID

但我猜我的大脑很慢。没收到。

【问题讨论】:

    标签: sql join greatest-n-per-group amazon-redshift


    【解决方案1】:

    您可以使用 Postgres 的DISTINCT ON

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

    对于 Redshift,您也许可以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
    

    【讨论】:

    • 嘿……在 AWS Redshift 上运行它。抱歉忘了提问题。不支持 Distinct On :(
    • 使用行号破解是我从未想过的事情。我很高兴它有效:)
    • 这太不可思议了!
    【解决方案2】:
    select t1.userid,
           t1.date,
           t1.event
    from table t1
    where t1.date= (select max(t2.date) 
                      from table t2
                      where t2.userid = t1.userid);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 2016-04-07
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 2013-05-25
      相关资源
      最近更新 更多