SQL Server - Round TIME值到下一分钟

时间:2012-02-14 09:28:03

标签: sql sql-server-2008 tsql rounding sqldatetime

我发现很多关于舍入“下降”时间值的帖子(例如https://stackoverflow.com/a/6667041/468823),但我有另一个问题:我想要更高的分钟而不是更低的分钟,我该怎么办? / p>

我的代码:

SELECT

 PA.ORE AS TOT_HOURS,  
 CAST(CAST(PA.ORA_INIZIO AS DATETIME) AS TIME) AS BEGIN_TIME,
 CAST(dateadd(minute, datediff(minute, 0, (CAST(PA.ORA_INIZIO AS DATETIME))), 0) AS TIME) AS BEGIN_TIME_ROUNDED


FROM PRG_ATTIVITA PA INNER JOIN PRG_TIPI_ATTIVITA PTA ON  PA.ID_TIPO_ATTIVITA = PTA.ID_TIPO_ATTIVITA
                     INNER JOIN PER_ANAGRAFICA PAN ON PA.ID_DIPENDENTE = PAN.ID_DIPENDENTE
WHERE PA.ID_PROGETTO = 1431 and pta.DESCR_TIPO_ATTIVITA like 'F-%remoto%' and ID_ATTIVITA = 41772 

ORDER BY  PA.DATA_ATTIVITA

我的结果如下:

    TOT_HOURS   BEGIN_TIME          BEGIN_TIME_ROUNDED
    1.50        15:59:59.9970000    15:59:00.0000000

我想要BEGIN_TIME_ROUNDED = 16:00:00.0000000

注意: 1.我必须转换我的数据{CAST(PA.ORA_INIZIO AS DATETIME)},因为在数据库中我有时间数据作为浮点值 2. BEGIN_TIME是转换后我的时间值的实际值

5 个答案:

答案 0 :(得分:3)

刚过CAST到smalldatetime四舍五入到最接近的分钟

SELECT 
    CAST(CAST('15:59:59.9970000' AS time) AS smalldatetime),
    CAST(CAST('15:59:30.0030000' AS time) AS smalldatetime),
    CAST(CAST('15:59:30.0000000' AS time) AS smalldatetime),
    CAST(CAST('15:59:29.9970000' AS time) AS smalldatetime),
    CAST(CAST('15:59:00.0030000' AS time) AS smalldatetime)

DATEADD / DATEDIFF用于截断一些时间单位

编辑,误读问题

只需修改您当前的CAST

即可
CAST(
 DATEADD(minute,
         DATEDIFF(minute, 
                  0, 
                  CAST(PA.ORA_INIZIO AS DATETIME)
                 ) + 1, 
         0
         )
     AS TIME)

答案 1 :(得分:3)

SELECT  DATEADD(MINUTE, CEILING(DATEDIFF(SECOND, 0, CAST(CAST(PA.ORA_INIZIO AS DATETIME) AS TIME)) / 60.0), DATEDIFF(DAY, 0, PA.ORA_INIZIO)) AS BEGIN_TIME_ROUNDED

答案 2 :(得分:1)

不知道SQL Server是否能够很好地回答,但如果没有人通过更实际的方式来实现这一点,那么你可以在将其向下舍入之前添加1分钟。如果您还需要正确处理整数输入值,请添加0.999分钟。

答案 3 :(得分:1)

declare @t time 
set @t = '10:28:00.001'
select cast(dateadd(millisecond, 29999, @t) as smalldatetime)

答案 4 :(得分:0)

如果你想将DATETIME d舍入到最近的分钟,你可以这样做:

CONVERT(DATETIME, CONVERT(SMALLDATETIME,
  DATEADD(minute, CASE WHEN d = CONVERT(SMALLDATETIME, d) THEN 0 ELSE 1 END,
  d)))