下舍入,圓最近&圍捕到最近的15分鐘
DATEADD(minute, (DATEDIFF(minute, 0, dateTimeX )/15) * 15, 0) AS dateTimeRoundDown
DATEADD(minute, (DATEDIFF(minute, 0, DATEADD(second, (15 * 60)/2, dateTimeX))/15) * 15, 0) AS dateTimeRoundNearest
DATEADD(minute, (DATEDIFF(minute, 0, DATEADD(minute, 15 , dateTimeX))/15) * 15, 0) AS dateTimeRoundUp
回合下來
DATEADD(minute, (DATEDIFF(minute, 0, dateTimeX)/15) * 15, 0) AS dateTimeRoundDown
獲得以分鐘爲單位的偏移量(分鐘數,因爲基地日期):
DATEDIFF(minute, 0, dateTimeX)
圓降至15分鐘塊由整數分割:
DATEDIFF(minute, 0, dateTimeX)/15) * 15
添加基追溯到以分鐘:
DATEADD(minute, (DATEDIFF(minute, 0, dateTimeX)/15) * 15, 0)
回合最近
DATEADD(minute, (DATEDIFF(minute, 0, DATEADD(second, (15 * 60)/2, dateTimeX))/15) * 15, 0) AS dateTimeRoundNear
2分之15分鐘被添加到偏移量。
由於整數除法需要秒數。
圍捕
DATEADD(minute, (DATEDIFF(minute, 0, DATEADD(minute, 15, dateTimeX))/15) * 15, 0) AS dateTimeRoundUp
15分鐘被添加到偏移
基準日期
我一般使用0基準日,其是SQL Server的 '曆元'
SELECT DATEADD(minute, 0, 0) -- '1900-01-01 00:00:00.000'
由於DATEADD()& DATEDIFF()對參數使用INT(32位)的SQL Server數據類型,因此對於日期很遠的將來,這可能會導致溢出。
使用另一個固定日期,例如'2010-01-01',將避免溢出。
所選擇的基本日必須具有的00:00:00
時間部分使用基日期和整數除法,沒有鑄造&不需要浮點運算。
單元測試
DECLARE @start DATETIME = '2017-04-20 21:00:00'
DECLARE @end DATETIME = '2017-04-20 22:00:00'
;WITH CTE_dateTimes AS
(
SELECT @start AS dateTimeX
UNION ALL
SELECT DATEADD(minute, 1, dateTimeX)
FROM CTE_dateTimes
WHERE DATEADD(minute, 1, dateTimeX) <= @end
)
SELECT dateTimeX,
DATEADD(minute, (DATEDIFF(minute, 0, dateTimeX )/15) * 15, 0) AS dateTimeRoundDown,
DATEADD(minute, (DATEDIFF(minute, 0, DATEADD(second, (15 * 60)/2, dateTimeX))/15) * 15, 0) AS dateTimeRoundNearest,
DATEADD(minute, (DATEDIFF(minute, 0, DATEADD(minute, 15 , dateTimeX))/15) * 15, 0) AS dateTimeRoundUp
FROM CTE_dateTimes
的可能的複製[如何輪T-SQL一個時間](http://stackoverflow.com/questions/249794/how-to-round-a-time -in-T-SQL) – Paddy