如果时间值距离最近的小时1分钟,我想将SQL时间舍入到最接近的小时。 (时间为24小时时钟格式)
例如
23:59 - > 00:00
11:30 - > 11:30
03:59 - > 04:00
01:15 - > 01:15
12:59 - > 13:00
这是我到目前为止所能做到的,但它只是四舍五入到最接近的1分钟。
declare @t time
declare @t2 time
set @t = '23:59:00.0000000';
set @t2 = '23:30:00.0000000';
select cast(dateadd(millisecond, 29999, @t) as smalldatetime) as T1, cast(dateadd(millisecond, 29999, @t2) as smalldatetime) as T2
答案 0 :(得分:1)
如果您尝试添加一分钟然后测试结果,则可以做出决定:
SELECT
cast(dateadd(millisecond, 29999, @t) as smalldatetime) as T1,
cast(dateadd(millisecond, 29999, @t2) as smalldatetime) as T2
,CASE WHEN SUBSTRING(CAST(DATEADD(MINUTE, 1, @t) as nvarchar(15)),4,2) = '00' THEN DATEADD(MINUTE, 1, @t) ELSE @t END
,CASE WHEN SUBSTRING(CAST(DATEADD(MINUTE, 1, @t2) as nvarchar(15)),4,2) = '00' THEN DATEADD(MINUTE, 1, @t2) ELSE @t2 END
答案 1 :(得分:1)
这使用case语句来检查分钟(不是@GordonLinoff :)小时是59还是0,如果是,则返回四舍五入到最接近小时的时间。否则它只是返回时间。这是一些示例代码
declare @t table (t time);
insert @t (t) values
('22:58:00'),
('22:58:30'),
('22:59:00'),
('22:59:30'),
('23:00:00'),
('23:00:30'),
('23:01:00'),
('23:01:30')
select
t,
-- just return the time rounded to the nearest hour
cast (dateadd(hour, datediff(hour, 0, dateadd(mi, 30, t)), 0) as time) as NearestHour,
-- return the time rounded to the nearest hour ONLY IF IT"S WITHIN ONE MINUTE OF THE HOUR
case when datepart (minute, t) in (0, 59)
then cast (dateadd(hour, datediff(hour, 0, dateadd(mi, 30, t)), 0) as time)
else t
end as Rounded
from @t
结果如下:
t NearestHour Rounded
---------------- ---------------- ----------------
22:58:00.0000000 23:00:00.0000000 22:58:00.0000000
22:58:30.0000000 23:00:00.0000000 22:58:30.0000000
22:59:00.0000000 23:00:00.0000000 23:00:00.0000000
22:59:30.0000000 23:00:00.0000000 23:00:00.0000000
23:00:00.0000000 23:00:00.0000000 23:00:00.0000000
23:00:30.0000000 23:00:00.0000000 23:00:00.0000000
23:01:00.0000000 23:00:00.0000000 23:01:00.0000000
23:01:30.0000000 23:00:00.0000000 23:01:30.0000000
答案 2 :(得分:0)
这似乎是一个奇怪的要求 - 只是摆脱了60分钟中的一分钟。但case
陈述应该做你想做的事情:
select (case when datepart(hour, time) = 59
then dateadd(hour, datediff(hour, 0, @t) + 1, 0)
else @t
end)
答案 3 :(得分:0)
使用这个想法:
select case when datepart(hh,dateadd(minute,1,convert(time,'10:59'))) <> datepart(hh,convert(time,'10:59')) then dateadd(minute,1,convert(time,'10:59'))
else convert(time,'10:59') end