查找2个日期和2个日期之间的记录如果未找到,则返回日期最小的记录

时间:2017-04-12 08:30:24

标签: sql

我有一张像

这样的表格
Name       DateOfBirth
--------------------------------
Ramesh     17/04/1983

Pavan      16/03/1980

Rakesh     18/03/1975

Nadeem     19/05/1974

Kalam      20/08/2973 

我正在编写一个SP,其伪代码如下:

我将日期作为输入参数传递给此SP

  1. 如果找到@InputDate,则SP应返回记录
  2. 如果@InputDate小于表中的最小日期,则应返回日期最小的记录
  3. 如果找不到@InputDate,但它介于最小和最小之间。列中的最大值然后应该返回稍后会丢失的记录

    • 是否可以在单个语句中编写逻辑?
    • 完成此任务的最佳方式

2 个答案:

答案 0 :(得分:2)

我认为下面的查询(在MySQL中)提供了你想要的东西:

SELECT Name, DateOfBirth
FROM mytable
WHERE DateOfBirth >= @mydate
ORDER BY DateOfBirth LIMIT 1

案例1 ,输入:

@mydate = '1972-03-16'

输出:

Name,   DateOfBirth
-------------------
Nadeem, 1974-05-19

案例2 ,输入:

@mydate = '1980-03-16'

输出:

Name,   DateOfBirth
-------------------
Pavan,  1980-03-16

案例3 ,输入:

@mydate = '1982-03-16'

输出:

Name,    DateOfBirth
-------------------
Ramesh,  1983-04-17

案例4 ,输入:

@mydate = '2982-03-16'

输出:

Name,    DateOfBirth
-------------------
No records returned

答案 1 :(得分:0)

是的,你可以。首先,让我们看看如何获​​得具有最小和最大日期的记录:

<强>最小

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所有可能的值。最后一步是修改选择以仅获取所需记录的NameDateOfBirth。如果没有匹配且日期不小于最小值且不大于最大值,则将返回null s。为此,我们需要使用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。

警告:没有任何代码经过测试,如果有任何拼写错误,请告诉我。