Sql 对日期时间应用底限,底限不是标准的,例如每 2 小时,每 2 天等

Sql applying a floor to Datetime, Where the floor is not standard e.g. every 2 hours, every 2 day etc

目标: 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]

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

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

将日期解构为多个部分,然后使用必要的部分重建它,调整需要 floor 的部分。

要将整数值乘以乘数,只需除以乘数,然后再乘以它即可。这依赖于整数除法截断除法结果,例如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 )