从数据库中检索每个用户的倒数第二条记录

时间:2012-09-07 20:45:33

标签: mysql sql oracle

我有一个表,其中包含用户名,更新日期和状态,如下所示:

名称| Updated_on |状态

akg     29-NOV-10       Active
akg     13-JAN-12       NonActive
akg     10-MAR-12       Active
ems     23-JUL-12       NonActive
ems     10-SEP-10       Active
tkp     10-SEP-10       NonActive
tkp     13-DEC-10       Active
tkp     02-JUL-12       NonActive
tkp     24-SEP-10       Active
aron    12-JAN-11       NonActive
aron    07-NOV-11       Active
aron    25-JUN-12       NonActive

在此表中,每次更改状态时都会更新用户状态(即username可以包含许多条目,如表中所示。

我想为每个用户提供第二个最新更新记录。即对于上表,结果应为:

名称| Updated_on |状态

akg     13-JAN-12       NonActive
ems     10-SEP-10       Active
tkp     13-DEC-10       Active
aron    07-NOV-11       Active

我真的很困惑,因为我想获得每个用户的记录。

有没有可用于此的查询?

谢谢

3 个答案:

答案 0 :(得分:1)

SELECT * FROM (
  SELECT
    rounda.*
  FROM
    userstatus AS rounda
    INNER JOIN userstatus AS roundb
      ON rounda.name=roundb.name
      AND rounda.Updated_on<roundb.Updated_On
  ORDER BY Updated_on DESC
) AS baseview
GROUP BY name

请参阅sqlfiddle

答案 1 :(得分:1)

你可以尝试一下,它有点冗长,但它有效:

SELECT
  name,
  max(Updated_on) as Updated_on,
  STATUS
FROM userstatus a
  WHERE (name, Updated_on) not in
  (select name, max(Updated_on) FROM userstatus group by name)
group by name, status
HAVING UPDATED_ON =
  (SELECT MAX(UPDATED_ON) FROM userstatus b where a.name = b.name
   and (b.name, b.Updated_on) not in
  (select name, max(Updated_on) FROM userstatus group by name)
  group by name);

Sqlfiddle

答案 2 :(得分:1)

用Oracle标记这个(也是):

select name, updated_on, status
from (
  select name, updated_on, status,
         row_number() over (partition by name order by updated_on desc) as rn,
         count(*) over (partition by name) as max_rn
  from userstatus
) 
where rn = max_rn - 1 
   or max_rn = 1;

这实际上适用于广泛的DBMS(包括Oracle) - 而不是MySQL。