您可以使用许多功能来做到这一点:
WITH D AS
( SELECT CURRENT_TIMESTAMP [DateField]
UNION ALL
SELECT DATEADD(MINUTE, 5, CURRENT_TIMESTAMP)
)
SELECT DATEADD(MINUTE, (10 * FLOOR(DATEPART(MINUTE, DateField) / 10.0)) - DATEPART(MINUTE, DateField), DATEADD(MINUTE, DATEDIFF(MINUTE, 0, DateField), 0)) AS RoundedDate
FROM D
其要点是去除 10 分钟间隔后的分钟数,并从实际分钟数中减去(删除秒数)。
这可以通过将一些函数移动到连接来稍微整理一下。但是,我认为这不会提供任何性能提升(根本没有进行任何测试)
;WITH T AS
( SELECT Number,
(10 * FLOOR(Number / 10.0)) - Number [RoundedDifference]
FROM ( SELECT ROW_NUMBER() OVER(ORDER BY Object_ID) - 1 [Number]
FROM sys.All_Objects
) n
WHERE Number < 60
), D AS
( SELECT CURRENT_TIMESTAMP [DateField]
UNION ALL
SELECT DATEADD(MINUTE, 5, CURRENT_TIMESTAMP)
)
SELECT DateField,
DATEADD(MINUTE, RoundedDifference, DATEADD(MINUTE, DATEDIFF(MINUTE, 0, DateField), 0)) [RoundedDate]
FROM D
INNER JOIN T
ON DATEPART(MINUTE, DateField) = Number