您可以像这样四舍五入到任何给定的分钟数:
DateAdd(Minute, (DateDiff(minute, 0, getutcdate() )/15) * 15, 0)
getutcdate()
您可以使用日期列、变量或表达式来代替使用。此外,分钟数可以是变量。
declare @minutesQuantize int set @minutesQuantize = 15
DateAdd(Minute, (DateDiff(minute, 0, getutcdate() )/@minutesQuantize) * @minutesQuantize, 0)
唯一的规则是日期差必须适合整数,即小于 20 亿。这意味着如果没有更复杂的表达式,您将无法做到秒或毫秒。
如果您需要秒或毫秒,请执行以下操作:
dateadd(ms, (datediff(ms, dateadd(day, datediff(day, 0, @date), 0), @date)/@msInterval)*@msInterval, dateadd(day, datediff(day, 0, @date), 0))
或者,如果你想把它包装成一个函数:
create function dbo.DateRoundMinutes(@dt datetime, @minutes int)
returns datetime
as begin
return DateAdd(Minute, (DateDiff(minute, 0, @dt )/@minutes) * @minutes, 0)
end
go
create function dbo.DateRoundMilliseconds(@dt datetime, @ms int)
returns datetime
as begin
return dateadd(ms, (datediff(ms, dateadd(day, datediff(day, 0, @dt), 0), @dt)/@ms)*@ms, dateadd(day, datediff(day, 0, @dt), 0))
end
您可以像这样使用它:
select t.dt,
dbo.DateRoundMilliseconds(dt, 500) dt0_5Second, -- Half second
dbo.DateRoundMilliseconds(dt, 5000) dt5second, -- 5 second
dbo.DateRoundMilliseconds(dt, 15000) dt15Second,
dbo.DateRoundMilliseconds(dt, 90000) dt90Second,
dbo.DateRoundMinutes(dt, 2) dt2Minute,
dbo.DateRoundMinutes(dt, 5) dt5Minute,
dbo.DateRoundMinutes(dt, 15) dt15Minute,
dbo.DateRoundMinutes(dt, 90) dt90Minute
from
/* some table having a column dt */