日期:2014-05-16  浏览次数:20389 次

求一条SQL在一个表中查出不同的人最后一条记录
表结构打比方 就 ID,USID,TIME,B1,B2,B3
求一条SQL 查询出这张表中不同的人的最后一条记录
------解决方案--------------------

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

------解决方案--------------------
这个适合2005及以后的版本:
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)