code-prettify

2014年3月27日 星期四

SQL DATEDIFF 日期差異,同一週、上一週、上上週,指定星期幾為起啟日。

一般來說,希望找到兩個日期是不是同一週可以使用 DATEDIFF 函式,
DATEDIFF(ww, @date1, @date2)

回傳值 0 表示同一週,1 表示 date1 是 date2 上一週,2 表示是上上週,-1 則表示是下一週,-2 是下下週。

而預設是以星期日為一週的開始,想說指定 SET DATEFIRST 1 來改變星期一為起始日。
但是怎麼設定都沒有效果。

上網路查,結果 MSDN 寫著「Specifying SET DATEFIRST has no effect on DATEDIFF. DATEDIFF always uses Sunday as the first day of the week to ensure the function is deterministic.」。

所以 DATEFIRST 對於 DEATEDIFF 是無效的。

那怎麼辦呢?網友已經提供了解法,解決了這個問題。

DATEDIFF(ww, DATEADD(dd, -@@DATEFIRST, @d1), DATEADD(dd, -@@DATEFIRST, @d2))

範例:
DECLARE @d1 DATETIME
DECLARE @d2 DATETIME
SET @d1 = '2014/10/05'
SET @d2 = '2014/10/06'

SET DATEFIRST 1

SELECT DATEDIFF(ww, DATEADD(dd, -@@DATEFIRST, @d1), DATEADD(dd, -@@DATEFIRST, @d2))

參考資料:
DATEDIFF (Transact-SQL)
http://technet.microsoft.com/en-us/library/ms189794.aspx

Is it possible to set start of week for T-SQL DATEDIFF function?
http://stackoverflow.com/questions/1101892/is-it-possible-to-set-start-of-week-for-t-sql-datediff-function

problem with Datediff and datefirst
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/8cc3493a-7ae5-4759-ab2a-e7683165320b/problem-with-datediff-and-datefirst?forum=transactsql

沒有留言:

張貼留言