是的,可以。首先,讓我們看看你如何能得到有你的一套最小和最大的日期記錄:
敏:
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