日期:2014-05-18 浏览次数:20778 次
select top 1 * from tb order by abs(datediff(d,time,@time)) asc
------解决方案--------------------
declare @T table (time datetime,empname varchar(4),proId int) insert into @T select '2011-12-01','张三',1 union all select '2011-12-01','张三',2 union all select '2012-01-01','张三',3 union all select '2012-01-01','张三',4 union all select '2012-01-01','张三',5 union all select '2011-12-01','李四',1 union all select '2011-12-01','李四',2 declare @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 李四 1 2011-12-01 00:00:00.000 李四 2 2012-01-01 00:00:00.000 张三 3 2012-01-01 00:00:00.000 张三 4 2012-01-01 00:00:00.000 张三 5 */
------解决方案--------------------
DECLARE @EndDate DATETIME SET @EndDate = '2012-02-01' declare @T table (time datetime,empname varchar(4),proId int) insert into @T select '2011-12-01','张三',1 union all select '2011-12-01','张三',2 union all select '2012-01-01','张三',3 union all select '2012-01-01','张三',4 union all select '2012-01-01','张三',5 union all select '2011-12-01','李四',1 union all select '2011-12-01','李四',2 SELECT * FROM @T A WHERE time = (SELECT TOP 1 time FROM @T WHERE empname = A.empname AND time <=@EndDate ORDER BY time DESC)