2010-05-20 14 views
2

我正在比較兩個日期並試圖確定兩個日期的最大值。空日期將被視爲低於有效日期。我正在使用下面的案例陳述,它適用於 - 但感覺非常低效和笨重。有沒有更好的辦法?T-SQL確定日期最大值的更好方法(佔空位)

update @TEMP_EARNED 
set nextearn = case when lastoccurrence is null and lastearned is null then null 
        when lastoccurrence is null then lastearned 
        when lastearned is null then lastoccurrence 
        when lastoccurrence > lastearned then lastoccurrence 
        else lastearned end; 

(這是在MS SQL 2000,僅供參考。)

回答

6
select c1, c2, 
     case when c1 > c2 then c1 else coalesce(c2,c1) end as max 
from twocol; 
+------+------+------+ 
| c1 | c2 | max | 
+------+------+------+ 
| NULL | NULL | NULL | 
| NULL | 2 | 2 | 
| 1 | NULL | 1 | 
| 1 | 2 | 2 | 
| NULL | NULL | NULL | 
| 2 | NULL | 2 | 
| NULL | 1 | 1 | 
| 2 | 1 | 2 | 
+------+------+------+ 

爲什麼這樣嗎?如果兩個操作數都不爲空,則我們得到一個「正常」的比較:當c1> c2時的「then」分支,當c1的時候分支爲< = c2。

在「else」分支上,我們調用coalesce,但作爲其第一個參數是非空c2,我們返回c2。

但是,如果任一操作數爲空,測試c1 > c2評估爲false,並且我們返回coalesce(c2, c1)

如果空操作數是c1,我們得到c2,這是我們想要的,因爲我們是(對於這個問題)調用null是「小於」任何非空值。

如果空操作數是c2,我們得到c1。這很好,因爲C1是要麼不爲空,因而(對這個問題)「大於」空C2,或...

如果兩個操作數都爲空的,我們得到C1,但它不無論我們得到什麼,因爲兩者都是空的。

一個額外的好處是,這個成語適用於任何類型的工作,沒有進一步的思考或細節,operator >工作。

4

的最早日期SQL Server可以在一個時間字段存儲爲1753年1月1日,所以如果你只是算空自該日起,那麼你可以做一個單行:

set nextearn = case when coalesce(lastoccurrence, '1753-01-01 00:00') > coalesce(lastearned, '1753-01-01 00:00') then lastoccurrence else lastearned end; 

如果你的領域是SMALLDATETIME那麼最小的是1900年1月1日,因此將是:

set nextearn = case when coalesce(lastoccurrence, '1900-01-01 00:00') > coalesce(lastearned, '1900-01-01 00:00') then lastoccurrence else lastearned end; 
+1

對於datetime的SQL Server字段,可以存儲的最早日期爲1753年1月1日,http://msdn.microsoft.com/zh-cn/library/ms187819.aspx。Smalldatetime的最小值是1900年1月1日。因此,文本字符串中使用的最小值取決於類型。 – 2010-05-20 16:35:19

+0

我不知道,答案更新。 – 2010-05-20 16:45:01

1

嘗試此:

Set nextearn = Case When IsNull(lastoccurrence, 0) > IsNull(lastearned , 0) 
       Then lastoccurrence Else lastearned End 

在SQL Server所有時間被存儲爲兩個整數,opne表示(自1900年1月1日的天數)和THH其它表示的時間(秒數[SMALLDATETIME日期]或milleseconds [DateTime]自午夜起)...

這兩個數字組合爲Integer.DecimalFraction(DateInteger.TimePortion)。 因此,數字0.0代表1900年1月1日的午夜,2.5代表1900年1月3日的中午,等等......

在您的表達式中使用數字可以消除在將數字與數字進行比較之前解析字符串表示的需要代表其他日期...

相關問題