2017-04-12 84 views
3

我有一个表像找到2个日期及如果没有找到返回具有最小日期记录之间的记录

Name  DateOfBirth 
-------------------------------- 
Ramesh  17/04/1983 

Pavan  16/03/1980 

Rakesh  18/03/1975 

Nadeem  19/05/1974 

Kalam  20/08/2973 

我正在写一个SP,其伪代码下面给出:

我“M传递的日期这个SP作为输入参数

  1. 如果@InputDate被找到时,SP应该返回记录
  2. 如果@InputDate比吨最小日期较小他表然后用最小的日期记录应退还
  3. 如果没有找到@InputDate,但它是在列,然后应返回的将立即下降之后的记录的最小&最大值之间

    • 是否可以在单个语句中编写逻辑?
    • 最优化的方式来完成这项任务
+1

您正在使用哪种RDBMS? –

+0

任何数据库都会做 –

+0

当谈到日期/时间时,许多dbms与ANSI SQL不兼容...... – jarlh

回答

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 
+0

不错 - 这可以很容易地转换成SQL的其他变体。 –

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。为此,我们需要使用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。

警告:没有测试代码,如果有任何错别字,请告诉我。

相关问题