从表中获取每个用户的最新记录

时间:2017-08-20 23:24:07

标签: sql oracle oracle11g greatest-n-per-group

我有一个表user_status,它存储每个用户的状态,每次状态更改时,我都会在user_status表中显示状态。

id   status     created 
1    ACTIVE     08-10-2017 08:21:22
1    ACTIVE     08-10-2017 08:21:25
1    NON_ACTIVE 08-10-2017 08:22:23
2    NON_ACTIVE 08-10-2017 08:22:23
2    ACTIVE     08-11-2017 08:25:23
3    NON_ACTIVE 08-12-2017 08:23:23

我正在寻找的是基于创建日期的每个用户的最后状态 所以我看的输出是

id   status     created 
1    NON_ACTIVE 08-10-2017 08:22:23
2    ACTIVE     08-11-2017 08:25:23
3    NON_ACTIVE 08-12-2017 08:23:23

一旦我这样做,我也有兴趣知道是否有办法获得每个用户的倒数第二个状态(一个在最后一个之前)状态

所以这个查询的输出我看起来是

1    ACTIVE     08-10-2017 08:21:25
2    NON_ACTIVE 08-10-2017 08:22:23
3    NON_ACTIVE 08-12-2017 08:23:23

任何建议,我

2 个答案:

答案 0 :(得分:0)

窗口有助于救援!

select t.*
from (select t.*,
             row_number() over (partition by id order by created desc) as seqnum,
             nth_value(status, 2) over (partition by id order by created desc) as second_status
      from t
     ) t
where seqnum = 1;

如果您不想要所有列,则可以使用条件聚合:

select t.id, max(t.created) as created,
       max(case when seqnum = 1 then status end) as last_status,
       max(case when seqnum = 2 then status end) as second_status,
from (select t.*,
             row_number() over (partition by id order by created desc) as seqnum
      from t
     ) t
group by id;

答案 1 :(得分:0)

查看您的查询,我建议一次性获取详细信息,而不是获取第一个状态,然后转到第二个状态。希望下面的代码段有用。

SELECT B.ID,
  B.STATUS,
  B.CREATED
FROM
  (SELECT A.ID,
    A.STATUS,
    CREATED,
    ROW_NUMBER() OVER(PARTITION BY A.ID ORDER BY A.CREATED DESC) RN
  FROM
    (SELECT 1 ID,'ACTIVE' STATUS,'08-10-2017 08:21:22' CREATED FROM DUAL
    UNION ALL
    SELECT 1 ID,'ACTIVE' STATUS,'08-10-2017 08:21:25' CREATED FROM DUAL
    UNION ALL
    SELECT 1 ID,'NON_ACTIVE' STATUS,'08-10-2017 08:22:23' CREATED FROM DUAL
    UNION ALL
    SELECT 2 ID,'NON_ACTIVE' STATUS,'08-10-2017 08:22:23' CREATED FROM DUAL
    UNION ALL
    SELECT 2 ID,'ACTIVE' STATUS,'08-11-2017 08:25:23' CREATED FROM DUAL
    UNION ALL
    SELECT 3 ID,'NON_ACTIVE' STATUS,'08-12-2017 08:23:23' CREATED FROM DUAL
    )A
  )B
WHERE B.RN IN (1,2);
/