我有一个表,其中包含用户名,更新日期和状态,如下所示:
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可以包含许多条目。
username
我想要每个用户的倒数第二个更新记录。即对于上表,结果应为:
akg 13-JAN-12 NonActive ems 10-SEP-10 Active tkp 13-DEC-10 Active aron 07-NOV-11 Active
我真的很困惑,因为我想获得每个用户的记录。
是否有任何查询可用于此目的?
谢谢
您可以尝试一下,它有点冗长,但是可以用:
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