将底线应用于Datetime的SQL,其中底线不是标准的,例如每2小时,每2天等

时间:2019-02-27 21:53:09

标签: sql sql-server datetime floor

目标:将底限应用到Datetime的SQL(底限不是标准的示例)每2个小时,每3天。而不是每小时,每天等的标准。

通用:用于比较每个收集期间的数据。当收集周期大于标准时间单位时。同时保留Datetime类型的好处。

转换示例:

将日期时间设置为2小时

+==========================+=======================+
|        WhenCreated       |       Time_Slot       |
+==========================+=======================+
|   2019-02-28 00:34:00    | 2019-02-28 00:00:00   |
+--------------------------+-----------------------+
|   2019-02-28 01:34:00    | 2019-02-28 00:00:00   |
+--------------------------+-----------------------+
|   2019-02-28 02:00:00    | 2019-02-28 02:00:00   |
+--------------------------+-----------------------+
|   2019-02-28 02:20:00    | 2019-02-28 02:00:00   |
+--------------------------+-----------------------+
|   2019-02-28 03:59:00    | 2019-02-28 02:00:00   |
+--------------------------+-----------------------+

当前解决方案:

在select语句内部,将基于[WhenCreated]创建一个新列[Time_Slot]:

left(convert(varchar(30), WhenCreated, 102),4) + '-' + left(right(convert(varchar(30), WhenCreated, 102),5),2) + '-' + right(convert(varchar(30), WhenCreated, 102),2) + ' ' +
    case
        when left(cast(cast(WhenCreated as time) as varchar(30)),2) in ('00','01') then '00:00:00.000'
        when left(cast(cast(WhenCreated as time) as varchar(30)),2) in ('02','03') then '02:00:00.000'
        when left(cast(cast(WhenCreated as time) as varchar(30)),2) in ('04','05') then '04:00:00.000'
        when left(cast(cast(WhenCreated as time) as varchar(30)),2) in ('06','07') then '06:00:00.000'
        when left(cast(cast(WhenCreated as time) as varchar(30)),2) in ('08','09') then '08:00:00.000'
        when left(cast(cast(WhenCreated as time) as varchar(30)),2) in ('10','11') then '10:00:00.000'
        when left(cast(cast(WhenCreated as time) as varchar(30)),2) in ('12','13') then '12:00:00.000'
        when left(cast(cast(WhenCreated as time) as varchar(30)),2) in ('14','15') then '14:00:00.000'
        when left(cast(cast(WhenCreated as time) as varchar(30)),2) in ('16','17') then '16:00:00.000'
        when left(cast(cast(WhenCreated as time) as varchar(30)),2) in ('18','19') then '18:00:00.000'
        when left(cast(cast(WhenCreated as time) as varchar(30)),2) in ('20','21') then '20:00:00.000'
        when left(cast(cast(WhenCreated as time) as varchar(30)),2) in ('22','23') then '22:00:00.000'
    end as [Time_Slot]

当前挑战: 当前的解决方案有效,但是很麻烦。必须有一个更简单的方法。那么什么是更好的方法呢?

编辑:修复了表中的错误。

1 个答案:

答案 0 :(得分:1)

将日期分解为多个部分,然后使用必要的部分对其进行重新构建,并调整需要下楼的部分。

要将整数值累加到乘数,只需将其除以乘数,然后再次将其乘以即可。这依赖于整数除法截断除法结果,例如5 / 2 = 2,因此5 / 2 * 2 = 4,即被截断为2的倍数。

因此,将WhenCreated的值设置为2小时的倍数:

DATETIMEFROMPARTS ( YEAR(WhenCreated), MONTH(WhenCreated), DAY(WhenCreated),
                    DATEPART(HOUR, WhenCreated) / 2 * 2, /*min*/0, /*sec*/0, /*milli*/0 )