time - Previous Hour or X Minutes in TSQL Snapping to Window -
in tsql, how can can previous hour snapping hour.
so example, if 2:33, how fields creationdate
(a datetime field) greater or equal 1:00 , less 2:00.
i to 10 minute intervals (snapping previous :00 - :10 if :14 example, or example, :50-:00 if :06).
this start , end of current hour:
select dateadd(hour, datepart(hour, getdate()), dateadd(day, 0, datediff(day, 0, getdate()))) , dateadd(hour, 1+datepart(hour, getdate()), dateadd(day, 0, datediff(day, 0, getdate())))
explanation: dateadd(day, 0, datediff(day, 0, getdate()))
gets start of today. add current hour that.
along same lines previous 10 minute block:
select dateadd(minute, datepart(minute, getdate()) / 10 * 10 - 10, dateadd(hour, datepart(hour, getdate()), dateadd(day, 0, datediff(day, 0, getdate())))) , dateadd(minute, datepart(minute, getdate()) / 10 * 10, dateadd(hour, datepart(hour, getdate()), dateadd(day, 0, datediff(day, 0, getdate()))))
or way of writing it:
declare @lowerbound datetime = dateadd(minute, datepart(minute, getdate()) / 10 * 10 - 10, dateadd(hour, datepart(hour, getdate()), dateadd(day, 0, datediff(day, 0, getdate())))) declare @upperbound datetime = dateadd(minute, datepart(minute, getdate()) / 10 * 10, dateadd(hour, datepart(hour, getdate()), dateadd(day, 0, datediff(day, 0, getdate())))) select @lowerbound, @upperbound
ps keep work on stack overflow performance!
Comments
Post a Comment