2016-03-24 43 views
1
Table1 
___________________ 
id Date 
1  2016/1/05 
2  2012/5/09 
3  2010/6/23 
4  2009/7/18 
5  2002/2/13 

试图编写一个SQL查询,该查询使用给定日期返回一个id。使用SQL Server 2014选择具有给定日期的单行

如果日期不在表中,它应该返回给定日期的最近日期。

所以....如果输入的日期是2016年1月2日,它将返回id为1,因为这是最接近的匹配

如果输入的日期是2003年2月12日,它将返回ID 5

回答

4

----编辑---

使用'abs'来获得“最接近”的数字。

declare @t1 as table (id int,date datetime) 
insert into @t1 select 1,'2016/1/05' 
insert into @t1 select 2,'2012/5/09' 
insert into @t1 select 3,'2010/6/23' 
insert into @t1 select 4,'2009/7/18' 
insert into @t1 select 5,'2002/2/13' 

declare @inputDate datetime = '2003/2/12' 
select top 1.id from @t1 order by abs(datediff(dd,date,@inputDate)) 

set @inputDate = '2016/1/02' 
select top 1.id from @t1 order by abs(datediff(dd,date,@inputDate)) 
+0

将无法​​正常工作,最接近的可能是更大的作为well.You就一定得两个日期,日期一个更大和一个较小,然后比较这两个看哪个是最接近的。 –

+0

哦是的,编辑.. –

+0

作品完美....谢谢你! –

0

你可以尝试伪代码这样的事情...

select id,date,min(days_cnt) 
(Select id , date,(date-input_date) as days_cnt from table) 
where days_cnt > 0 
相关问题