insert into test(username,time1,time2,num)
select 'as1','2010-09-08 10:50','2010-09-08 10:58','10' union
select 'as1','2010-09-08 10:50','2010-09-08 11:58','15' union
select 'as1','2010-09-08 11:30','2010-09-08 12:58','16' union
select 'as1','2010-09-08 11:30','2010-09-08 13:58','8' union
select 'as2','2010-09-08 13:50','2010-09-08 10:58','10' union
select 'as2','2010-09-08 13:50','2010-09-08 11:58','15' union
select 'as2','2010-09-08 11:30','2010-09-08 12:58','16' union
select 'as2','2010-09-08 11:30','2010-09-08 13:58','8' 根据username来先分组,然后取time1最大的那条记录,如果time1有相等的就取 time2较大的那条记录
结果如下
4 as1 2010-09-08 11:30:00.000 2010-09-08 13:58:00.000 8
8 as2 2010-09-08 13:50:00.000 2010-09-08 11:58:00.000 15除了以下这种方法,还有比较简便的写法吗?
select c.* from test c ,
(
select b.username, max(time2)time2 from test b,
(
select username, max(time1) time1 from test 
group by username
)a where b.username=a.username and b.time1=a.time1
group by b.username
)d where c.time2=d.time2 and c.username=d.username