有如下表记录:
ID Name EmailAddress LastLogon
100 test4 [email protected] 2007-11-25 16:31:26
13 test1 [email protected] 2007-3-22 16:27:07
19 test1 [email protected] 2007-10-25 14:13:46
42 test1 [email protected] 2007-11-20 14:20:10
45 test2 [email protected] 2007-4-25 14:17:39
49 test2 [email protected] 2007-5-25 14:22:36 用一句sql查询出每个用户最近一次登录的记录(每个用户只显示一条最近登录的记录)
ID Name EmailAddress LastLogon
100 test4 [email protected] 2007-11-25 16:31:26
13 test1 [email protected] 2007-3-22 16:27:07
19 test1 [email protected] 2007-10-25 14:13:46
42 test1 [email protected] 2007-11-20 14:20:10
45 test2 [email protected] 2007-4-25 14:17:39
49 test2 [email protected] 2007-5-25 14:22:36 用一句sql查询出每个用户最近一次登录的记录(每个用户只显示一条最近登录的记录)
-- Create table
create table THINK_TEST
(
ID VARCHAR2(50),
NAME VARCHAR2(20),
EMAILADDRESS VARCHAR2(50),
LASTLOGON VARCHAR2(50)
)
-- insert data
insert into think_test values('100','test4','[email protected]','2007-11-25 16:31:26 ');
insert into think_test values('13','test1','[email protected]','2007-3-22 16:27:07');
insert into think_test values('19','test1','[email protected]','2007-10-25 14:13:46');
insert into think_test values('42','test1','[email protected]','2007-11-20 14:20:10');
insert into think_test values('45','test2','[email protected]','2007-4-25 14:17:39');
insert into think_test values('49','test2','[email protected]','2007-5-25 14:22:36 ');
--preview date
select * from think_test;ID NAME EMAILADDRESS LASTLOGON
-------------------------------------------------- -------------------- -------------------------------------------------- --------------------------------------------------
100 test4 [email protected] 2007-11-25 16:31:26
13 test1 [email protected] 2007-3-22 16:27:07
19 test1 [email protected] 2007-10-25 14:13:46
42 test1 [email protected] 2007-11-20 14:20:10
45 test2 [email protected] 2007-4-25 14:17:39
49 test2 [email protected] 2007-5-25 14:22:36
--execute sql
select *
from(
select t.*,RANK() OVER (PARTITION BY t.name order by rownum desc) Rnk
from think_test t
) tt
where tt.rnk<2;ID NAME EMAILADDRESS LASTLOGON RNK
-------------------------------------------------- -------------------- -------------------------------------------------- -------------------------------------------------- ----------
42 test1 [email protected] 2007-11-20 14:20:10 1
49 test2 [email protected] 2007-5-25 14:22:36 1
100 test4 [email protected] 2007-11-25 16:31:26 1