当前位置: 代码迷 >> Sql Server >> MSSQL输入一个时间段,怎么得到离这个时间段最新的数据
  详细解决方案

MSSQL输入一个时间段,怎么得到离这个时间段最新的数据

热度:87   发布时间:2016-04-27 14:26:28.0
MSSQL输入一个时间段,如何得到离这个时间段最新的数据?
比如有如下表:
time empname proId  
2011-12-01 张三 1
2011-12-01 张三 2
2012-01-01 张三 3  
2012-01-01 张三 4  
2012-01-01 张三 5  

2011-12-01 李四 1
2011-12-01 李四 2


当我输入2012-02-01的时候,查询出来的数据应该是:

张三小于或等于2012-02-01最新数据为time:2012-01-01的数据,
李四则为:2011-12-01的数据。
最终查询的数据为:

time empname proId  
2012-01-01 张三 3  
2012-01-01 张三 4  
2012-01-01 张三 5  

2011-12-01 李四 1
2011-12-01 李四 2

求各位前辈帮帮忙,在线等。

------解决方案--------------------
SQL code
select top 1 * from tborder by abs(datediff(d,time,@time)) asc
------解决方案--------------------
SQL code
declare @T table (time datetime,empname varchar(4),proId int)insert into @Tselect '2011-12-01','张三',1 union allselect '2011-12-01','张三',2 union allselect '2012-01-01','张三',3 union allselect '2012-01-01','张三',4 union allselect '2012-01-01','张三',5 union allselect '2011-12-01','李四',1 union allselect '2011-12-01','李四',2declare @date varchar(10) set @date='2012-02-01'select * from @T t where abs(datediff(d,time,@date))=(select min(abs(datediff(d,time,@date))) from @T where empname=t.empname)/*time                    empname proId----------------------- ------- -----------2011-12-01 00:00:00.000 李四      12011-12-01 00:00:00.000 李四      22012-01-01 00:00:00.000 张三      32012-01-01 00:00:00.000 张三      42012-01-01 00:00:00.000 张三      5*/
------解决方案--------------------
SQL code
DECLARE @EndDate DATETIMESET @EndDate = '2012-02-01'declare @T table (time datetime,empname varchar(4),proId int)insert into @Tselect '2011-12-01','张三',1 union allselect '2011-12-01','张三',2 union allselect '2012-01-01','张三',3 union allselect '2012-01-01','张三',4 union allselect '2012-01-01','张三',5 union allselect '2011-12-01','李四',1 union allselect '2011-12-01','李四',2SELECT * FROM @T AWHERE time = (SELECT TOP 1 time FROM @T WHERE empname = A.empname AND time <[email protected] ORDER BY time DESC)
  相关解决方案