2017-04-12 77 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。

警告:沒有測試代碼,如果有任何錯別字,請告訴我。

相關問題