Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Precisa calcular por hora ou data arredondada no servidor sql


Você pode usar a mesma técnica para arredondar para qualquer intervalo de data. Isso depende da divisão inteira
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;