日期:2014-05-18  浏览次数:20717 次

求一SQL语句——取分组中时间最靠近当前时间值的行
表结构与数据:
UUID XX_ID STATUS UPDATE_TIME
1 1 1 2011/6/4 15:23
2 1 2 2011/10/4 11:22
3 1 1 2010/12/12 13:23
4 2 1 2011/6/4 16:23
5 2 2 2011/6/11 14:01
6 3 1 2011/9/11 14:01
7 3 2 2011/6/4 15:23
8 3 2 2011/8/4 15:23
9 4 1 2011/11/4 16:23
10 4 1 2011/12/11 14:01
要求:
按照XX_ID分组 然后取出每个分组中时间与当前时间最接近的一行数据
想要的结果:
 
UUID XX_ID STATUS UPDATE_TIME
3 1 1 2010/12/12 13:23
5 2 2 2011/6/11 14:01
6 3 1 2011/9/11 14:01
10 4 1 2011/12/11 14:01


------解决方案--------------------
SQL code
--> 测试数据:#
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
*/

------解决方案--------------------
SQL code
select * from tb t where UPDATE_TIME=(select max(UPDATE_TIME) from tb where XX_ID =t.XX_ID)

------解决方案--------------------
SQL code
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