日期:2014-05-18 浏览次数:20903 次
--> 测试数据:#
if object_id('tempdb.dbo.#') is not null drop table #
create table #(UUID int, XX_ID int, STATUS int, UPDATE_TIME datetime)
insert into #
select 1, 1, 1, '2011/6/4 15:23' union all
select 2, 1, 2, '2011/10/4 11:22' union all
select 3, 1, 1, '2010/12/12 13:23' union all
select 4, 2, 1, '2011/6/4 16:23' union all
select 5, 2, 2, '2011/6/11 14:01' union all
select 6, 3, 1, '2011/9/11 14:01' union all
select 7, 3, 2, '2011/6/4 15:23' union all
select 8, 3, 2, '2011/8/4 15:23' union all
select 9, 4, 1, '2011/11/4 16:23' union all
select 10, 4, 1, '2011/12/11 14:01'
select * from # t where UPDATE_TIME = (select top 1 UPDATE_TIME from # where XX_ID=t.XX_ID order by abs(datediff(second,getdate(),UPDATE_TIME)))
/*
UUID XX_ID STATUS UPDATE_TIME
----------- ----------- ----------- -----------------------
2 1 2 2011-10-04 11:22:00.000
5 2 2 2011-06-11 14:01:00.000
6 3 1 2011-09-11 14:01:00.000
10 4 1 2011-12-11 14:01:00.000
*/
------解决方案--------------------
select * from tb t where UPDATE_TIME=(select max(UPDATE_TIME) from tb where XX_ID =t.XX_ID)
------解决方案--------------------
create index indexname on tb(xx_id,UPDATE_TIME desc)
go
select *
from(
select *,
rn=row_number()over(partition by XX_ID order by UPDATE_TIME desc)
from tb)t
where rn=1