在SQL Server 2008中将舍入时间缩短到整秒

时间:2015-12-16 21:26:54

标签: sql sql-server time rounding

我有一个时间栏

Time
07:34:23.554
08:44:42.778
08:11:38.332

我想舍入秒字段,以便如果十进制后的值小于0.5则会向下舍入,如果十进制之后的值大于0.5则会向上舍入。

我想要的输出是

Time
07:34:24
08:44:43
08:11:38

感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:2)

您可以将其转换为TIME(0)

Declare @Time Table 
(   
    Time Time
) 

Insert  @Time 
        (Time)
Select  '07:34:23.554'  Union All 
Select  '08:44:42.778'  Union All 
Select  '08:11:38.332'

Select  Cast(Time as Time(0)) As RoundedTime, 
        Time 
From    @Time

输出:

RoundedTime Time
----------------------------
07:34:24    07:34:23.5540000
08:44:43    08:44:42.7780000
08:11:38    08:11:38.3320000

更永久的解决方案是将表格中的列的数据类型更改为TIME(0)

Declare @Time Table 
(   
    Time Time(0)
) 

Insert  @Time 
        (Time)
Select  '07:34:23.554'  Union All 
Select  '08:44:42.778'  Union All 
Select  '08:11:38.332'

Select  *
From    @Time

输出:

Time
--------
07:34:24
08:44:43
08:11:38