Cómo agrupar el tiempo por hora o por 10 minutos


Como cuando lo hago

SELECT [Date]
  FROM [FRIIB].[dbo].[ArchiveAnalog]
  GROUP BY [Date]

¿Cómo puedo especificar el período del grupo ?

MS SQL 2008

2a edición

Estoy tratando

SELECT MIN([Date]) AS RecT, AVG(Value)
  FROM [FRIIB].[dbo].[ArchiveAnalog]
  GROUP BY (DATEPART(MINUTE, [Date]) / 10)
  ORDER BY RecT

Cambiado %10 a / 10. ¿es posible hacer salida de fecha sin milisegundos ?

Author: TMS, 2011-02-15

9 answers

Finalmente hecho con

GROUP BY
DATEPART(YEAR, DT.[Date]),
DATEPART(MONTH, DT.[Date]),
DATEPART(DAY, DT.[Date]),
DATEPART(HOUR, DT.[Date]),
(DATEPART(MINUTE, DT.[Date]) / 10)
 174
Author: Cynede,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-28 08:38:23

Llego muy tarde a la fiesta, pero esto no aparece en ninguna de las respuestas existentes:

GROUP BY DATEADD(MINUTE, DATEDIFF(MINUTE, 0, date_column) / 10 * 10, 0)
  • Los términos 10 y MINUTE se pueden cambiar a cualquier número y DATEPART, respectivamente.
  • Es un valor DATETIME, que significa:
    • Funciona bien a través de largos intervalos de tiempo. (No hay colisión entre años.)
    • Incluirlo en la instrucción SELECT le dará a su salida una columna con una salida bastante truncada al nivel que especificar.
SELECT   DATEADD(MINUTE, DATEDIFF(MINUTE, 0, aa.[date]) / 10 * 10, 0) AS [date_truncated],
         COUNT(*) AS [records_in_interval],
         AVG(aa.[value]) AS [average_value]
FROM     [friib].[dbo].[archive_analog] AS aa
GROUP BY DATEADD(MINUTE, DATEDIFF(MINUTE, 0, aa.[date]) / 10 * 10, 0)
ORDER BY [date_truncated]
 25
Author: Michael,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-17 16:39:38

En T-SQL puedes:

SELECT [Date]
  FROM [FRIIB].[dbo].[ArchiveAnalog]
  GROUP BY [Date], DATEPART(hh, [Date])

O

Por minuto DATEPART(mi, [Date])

O

Por 10 minutos usar DATEPART(mi, [Date]) / 10 (como Timoteo sugirió)

 13
Author: tzup,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-03 09:44:00

Por un intervalo de 10 minutos, usted

GROUP BY (DATEPART(MINUTE, [Date]) / 10)

Como ya fue mencionado por tzup y Pieter888... para hacer un intervalo de horas, solo

GROUP BY DATEPART(HOUR, [Date])
 12
Author: Timothy Khouri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-22 12:18:45

La respuesta original que el autor dio funciona bastante bien. Solo para extender esta idea, puedes hacer algo como

group by datediff(minute, 0, [Date])/10

Que le permitirá agrupar por un período más largo que 60 minutos, digamos 720, que es medio día, etc.

 6
Author: Derek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-30 14:35:45

Debería ser algo como

select timeslot, count(*)  
from 
    (
    select datepart('hh', date) timeslot
    FROM [FRIIB].[dbo].[ArchiveAnalog]  
    ) 
group by timeslot

(No estoy 100% seguro de la sintaxis-soy más un tipo de Oráculo)

En Oracle:

SELECT timeslot, COUNT(*) 
FROM
(  
    SELECT to_char(l_time, 'YYYY-MM-DD hh24') timeslot 
    FROM
    (
        SELECT l_time FROM mytab  
    )  
) GROUP BY timeslot 
 4
Author: Frank Schmitt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-23 01:25:01

Para MySQL:

GROUP BY
DATE(`your_date_field`),
HOUR(`your_date_field`),
FLOOR( MINUTE(`your_date_field`) / 10);
 3
Author: nobilist,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-10 06:55:05

Mi solución es usar una función para crear una tabla con los intervalos de fechas y luego unir esta tabla a los datos que quiero agrupar usando el intervalo de fechas en la tabla. El intervalo de fechas se puede seleccionar fácilmente al presentar los datos.

CREATE FUNCTION [dbo].[fn_MinuteIntervals]
    (
      @startDate SMALLDATETIME ,
      @endDate SMALLDATETIME ,
      @interval INT = 1
    )
RETURNS @returnDates TABLE
    (
      [date] SMALLDATETIME PRIMARY KEY NOT NULL
    )
AS
    BEGIN
        DECLARE @counter SMALLDATETIME
        SET @counter = @startDate
        WHILE @counter <= @endDate
            BEGIN
                INSERT INTO @returnDates VALUES ( @counter )
                SET @counter = DATEADD(n, @interval, @counter)
            END
        RETURN
    END
 0
Author: user3193141,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-14 08:11:12

Para SQL Server 2012, aunque creo que funcionaría en SQL Server 2008R2, utilizo el siguiente enfoque para reducir el tiempo al milisegundo:

DATEADD(MILLISECOND, -DATEDIFF(MILLISECOND, CAST(time AS DATE), time) % @msPerSlice, time)

Esto funciona por:

  • Obteniendo el número de milisegundos entre un punto fijo y el tiempo objetivo:
    @ms = DATEDIFF(MILLISECOND, CAST(time AS DATE), time)
  • Tomando el resto de dividir esos milisegundos en rebanadas de tiempo:
    @rms = @ms % @msPerSlice
  • Agregando el negativo de ese resto al tiempo objetivo para obtener el segmento tiempo:
    DATEADD(MILLISECOND, -@rms, time)

Desafortunadamente, al igual que esto se desborda con microsegundos y unidades más pequeñas, por lo que los conjuntos de datos más grandes y finos tendrían que usar un punto fijo menos conveniente.

No he evaluado esto rigurosamente y no estoy en big data, por lo que su kilometraje puede variar, pero el rendimiento no fue notablemente peor que los otros métodos probados en nuestros equipos y conjuntos de datos, y el pago en la comodidad del desarrollador por rebanar arbitrariamente hace que valga la pena para nosotros.

 0
Author: tychon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-24 01:47:00