是的,可以。首先,让我们看看你如何能得到有你的一套最小和最大的日期记录:
敏:
select top 1 Name, DateOfBirth
from yourtable
order by DateOfBirth
最大:
select top 1 Name, DateOfBirth
from yourtable
order by DateOfBirth desc
这就是你怎么弄匹配记录:
select top 1 Name, DateOfBirth
from yourtable
where DateOfBirth = @InputDate
现在,让我们都在一起成一个查询:
select mymin.Name as myminName, mymin.DateOfBirth as myminDateOfBirth,
mymax.Name as mymaxName, myMax.DateOfBirth as mymaxDateOfBirth,
therecord.Name as therecordName, therecord.DateOfBirth as therecordDateOfBirth
from
(select top 1 Name, DateOfBirth
from yourtable
order by DateOfBirth) mymin
join
(select top 1 Name, DateOfBirth
from yourtable
order by DateOfBirth desc) mymax
on 1 = 1
left join yourtable therecord
on therecord.DateOfBirth = @InputDate
正如你所看到的,我们可以select
所有可能的值。最后一步是修改选择以获得理想记录的Name
和DateOfBirth
。如果没有匹配且日期不小于最小值且不大于最大值,则将返回null
。为此,我们需要使用case
- when
语法,就像这样:
select case (therecord.Name is null)
When 1 then (case mymin.DateOfBirth > @InputDate when 1 then mymin.Name
else case mymax.DateOfBirth < @InputDate when 1 then mymax.Name else null end)
Else therecord.Name
End as Name,
case (therecord.Name is null)
When 1 then (case mymin.DateOfBirth > @InputDate when 1 then mymin.DateOfBirth
else case mymax.DateOfBirth < @InputDate when 1 then mymax.DateOfBirth else null end)
Else therecord.DateOfBirth
End as DateOfBirth
from
(select top 1 Name, DateOfBirth
from yourtable
order by DateOfBirth) mymin
join
(select top 1 Name, DateOfBirth
from yourtable
order by DateOfBirth desc) mymax
on 1 = 1
left join yourtable therecord
on therecord.DateOfBirth = @InputDate
我以为你正在使用SQL Server。
警告:没有测试代码,如果有任何错别字,请告诉我。
您正在使用哪种RDBMS? –
任何数据库都会做 –
当谈到日期/时间时,许多dbms与ANSI SQL不兼容...... – jarlh