日期:2014-05-16 浏览次数:20445 次
create table test (id int,usid int,[time] datetime,b1 varchar(10),b2 varchar(10),b3 varchar(10))
insert into test
select 1,1,'2014-01-01','aaa','aaa','aaa' union all
select 2,2,'2014-01-02','bbb','bbb','bbb' union all
select 3,1,'2014-01-03','ccc','ccc','ccc' union all
select 4,3,'2014-01-04','ddd','ddd','ddd' union all
select 5,1,'2014-01-05','eee','eee','eee' union all
select 6,2,'2014-01-06','fff','fff','fff'
select a.*
from test a
inner join (
select usid ,[time]=max(time)
from test
group by usid
)b
on a.usid=b.usid and a.time=b.time
/*
4 3 2014-01-04 00:00:00.000 ddd ddd ddd
6 2 2014-01-06 00:00:00.000 fff fff fff
5 1 2014-01-05 00:00:00.000 eee eee eee
*/
select * from
(
select *,ROW_NUMBER() over(partition by USID order by [TIME] desc) as rn from [表名]
) t where rn=1
select ID,USID,TIME,B1,B2,B3
from
(
select *,
ROW_NUMBER() over(partition by usid order by time desc) rownum
from 表
)t
where rownum = 1
select * from 表 t
where id=(select max(id) from 表 where usid=t.usid)