0

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

姓名 | 更新_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可以有许多条目,如表中所示。

我想要每个用户的第二个最后更新的记录。即对于上表,结果应该是:

姓名 | 更新_on | 地位

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

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

有没有可以用于此的查询?

谢谢

4

3 回答 3

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

于 2012-09-07T20:57:05.993 回答
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

于 2012-09-07T20:59:29.007 回答
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。

于 2012-09-07T22:39:32.137 回答