Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

È necessario calcolare in base all'ora o alla data arrotondata nel server sql

È possibile utilizzare la stessa tecnica per arrotondare a qualsiasi intervallo di date. Questo si basa sulla divisione intera

SELECT
    DATEADD(minute, DATEDIFF(minute, 0, foo), 0),              -- whole minute
    DATEADD(minute, DATEDIFF(minute, 0, foo) / 5 * 5, 0),      -- 5 minute
    DATEADD(minute, DATEDIFF(minute, 0, foo) / 10 * 10, 0),    -- 10 minute
    DATEADD(minute, DATEDIFF(minute, 0, foo) / 15 * 15, 0),    -- 15 minute
    DATEADD(minute, DATEDIFF(minute, 0, foo) / 30 * 30, 0),    -- 30 minute

    DATEADD(hour, DATEDIFF(hour, 0, foo), 0),                  -- whole hour
    DATEADD(hour, DATEDIFF(hour, 0, foo) / 2 * 2, 0),          -- 2 hour

    DATEADD(day, DATEDIFF(day, 0, foo), 0),                    -- whole day
    DATEADD(day, DATEDIFF(day, 0, foo) / 5 * 5, 0),            -- 5 day
    DATEADD(day, DATEDIFF(day, 0, foo) / 10 * 10, 0),          -- 10 day

    DATEADD(month, DATEDIFF(month, 0, foo), 0),                -- whole month
    DATEADD(month, DATEDIFF(month, 0, foo) / 2 * 2, 0)         -- 2 month
FROM
    @dates;