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
求各位前辈帮帮忙,在线等。
[解决办法]
select top 1 * from tborder by abs(datediff(d,time,@time)) asc
[解决办法]
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*/
[解决办法]
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 <=@EndDate ORDER BY time DESC)