如何按5分钟的时间间隔对列进行分组?例如:
Date_Timing team --------------------------------------- 2016-10-16-10:32:08 baseball 2016-10-16-10:34:11 baseball 2016-10-16-10:35:12 baseball 2016-10-16-10:41:14 Soccer 2016-10-16-10:43:15 soccer 2016-10-16-10:44:19 soccer
,结果应该是;
team -------- baseball soccer Soccer
提前致谢。
答案 0 :(得分:0)
试试这个:
SELECT team
FROM table_name
WHERE Date_Timing BETWEEN DATEADD('ss',-5,GETDATE()) AND GETDATE()
GROUP BY team
这将获得最后5秒的记录并按团队分组
答案 1 :(得分:0)
您可以如下所示:
DECLARE @Tbl TABLE (Date_Timing DATETIME, team VARCHAR(50))
INSERT INTO @Tbl
VALUES
('2016-10-16 10:32:08', 'baseball'),
('2016-10-16 10:34:11', 'baseball'),
('2016-10-16 10:35:12', 'baseball'),
('2016-10-16 10:41:14', 'Soccer'),
('2016-10-16 10:43:15', 'soccer'),
('2016-10-16 10:44:19', 'soccer')
;WITH CTE1 AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY Date_Timing) AS RowId FROM @Tbl ),
CTE2
AS
(
SELECT
A.Date_Timing ,
A.team,
DENSE_RANK() OVER (ORDER BY MIN(B.RowId)) [Group]
FROM
CTE1 A CROSS JOIN CTE1 B
WHERE
ABS(DATEDIFF(MINUTE, A.Date_Timing, B.Date_Timing)) BETWEEN 0 AND 5 -- 5 min
GROUP BY
A.Date_Timing ,
A.team
)
SELECT
A.team COLLATE SQL_Latin1_General_CP1_CS_AS AS team
FROM
CTE2 A
GROUP BY
A.team COLLATE SQL_Latin1_General_CP1_CS_AS,
A.[Group]
结果:
team
----------------
baseball
Soccer
soccer
答案 2 :(得分:0)
按5分钟的时间间隔分组很大程度上取决于第一个间隔时隙的开始。您可以按照SQL Server纪元的分钟数除以5分组,如下例所示
DECLARE @Tbl TABLE (Date_Timing DATETIME, team VARCHAR(50))
INSERT INTO @Tbl
VALUES
('2016-10-16 10:32:08', 'baseball'),
('2016-10-16 10:34:11', 'baseball'),
('2016-10-16 10:35:12', 'baseball'),
('2016-10-16 10:41:14', 'Soccer'),
('2016-10-16 10:43:15', 'soccer'),
('2016-10-16 10:44:19', 'soccer')
DECLARE @start_interval datetime
SET @start_interval = '00:01'
select
team COLLATE SQL_Latin1_General_CP1_CS_AS as team,
DATEADD(MINUTE,5*floor(DATEDIFF(MINUTE,@start_interval,Date_Timing)/5),@start_interval) as time_interval
from @Tbl
group by team COLLATE sql_latin1_general_cp1_cs_as,
floor(DATEDIFF(MINUTE,@start_interval,Date_Timing)/5)
@start_interval设置为'00:01'表示我们从SQL Server纪元后的第一分钟开始间隔,因此根据您的数据,插槽将为10:31-10:35:59.999,10:36-10 :40:59.999,10:41-10:45:59.999等等。尝试根据需要设置开始时间段。