日期:2014-05-18 浏览次数:20664 次
create table tb (id int, time datetime,location varchar(50),name varchar(50)) insert into tb select 1,'2012-2-1 22:12:00','合肥','合肥' insert into tb select 2,'2012-2-1 22:12:03','合肥','合肥' insert into tb select 3,'2012-2-1 22:13:00','合肥','合肥' insert into tb select 4,'2012-2-2 22:15:06','合肥','合肥' insert into tb select 5,'2012-2-2 22:15:50','合肥','合肥' with aa as( select time,case when datediff(ss,'2012/02/02 22:15:00' ,time)<0 then -datediff(ss,'2012/02/02 22:15:00',time) else datediff(ss,'2012/02/02 22:15:00',time) end aa from tb where time!='2012/02/02 22:15:00') select * from tb where time in (select time from aa a where not exists(select 1 from aa b where a.aa>b.aa))
------解决方案--------------------
if Object_id('tb1') is not null Drop table tb1; go create table tb1([ID] int primary key, [Time] datetime, [Location] nvarchar(50), [Name] nvarchar(50)); go insert into tb1 select 1, '2012/02/01 22:12:00', '合肥', '合肥' union all select 2, '2012/02/01 22:12:03', '合肥', '合肥' union all select 3, '2012/02/01 22:13:00', '合肥', '合肥' union all select 4, '2012/02/02 22:15:06', '合肥', '合肥' union all select 5, '2012/02/02 22:15:50', '合肥', '合肥'; select * from tb1; declare @t datetime; Set @t = '2012/02/02 22:15:00'; select top 1* from tb1 order by abs(datediff(ms, @t, [Time])) /* ID Time Location Name ----------- ----------------------- --------------- ----------------- 4 2012-02-02 22:15:06.000 合肥 合肥 */