近时分组数据行

时间:2013-08-18 12:50:02

标签: sql-server datetime group-by

这是我面临的问题: 我有一个包含行的大表,我想在近时将它们分组,更具体地说,时间差小于2分钟,例如如下 使用以下输入数据:

  • A 16:01:01
  • B 16:01:20
  • C 16:14:02
  • D 16:15:01
  • E 16:20:02

预期结果是

16:01:01 2
16:14:02 2
16:20:02 1

3 个答案:

答案 0 :(得分:1)

如果你正在使用SQL Server 2012,那么你很幸运,你可以使用lag函数和滚动总计sum

with cte as (
    select
        case
            when datediff(mi, lag(data) over (order by data), data) <= 1 then 0
            else 1
        end as ch,
        data
    from test
), cte2 as (
    select
        data, sum(ch) over (order by data) as grp
    from cte
)
select
    min(data) as data, count(*) as cn
from cte2
group by grp

sql fiddle demo

答案 1 :(得分:0)

Declare @m_TestTable table
(
DateRecorded datetime

)

Insert into @m_TestTable Values ('16:01:01' )
Insert into @m_TestTable Values ('16:01:20' )
Insert into @m_TestTable Values ('16:14:02' )
Insert into @m_TestTable Values ('16:15:01' )
Insert into @m_TestTable Values ('16:20:01' );

With tblDifference as
(
Select Row_Number() OVER (Order by DateRecorded) as RowNumber,DateRecorded from @m_TestTable
)

select cur.DateRecorded as prvD, prv.DateRecorded as prvC, dateDiff(n, cur.DateRecorded,prv.DateRecorded)  from tblDifference cur LEFT OUTER JOIN tblDifference prv 
ON cur.RowNumber = prv.RowNumber + 1

这将为您提供2行之间的分钟时差。您可以选择时间差小于2分钟的任何行。它还会为您提供上限和下限值。

找到距离接近2分钟的任何值都应该是有用的。

prvD                    prvC                    Diff
1900-01-01 16:01:01.000 NULL                    NULL
1900-01-01 16:01:20.000 1900-01-01 16:01:01.000 0
1900-01-01 16:14:02.000 1900-01-01 16:01:20.000 -13
1900-01-01 16:15:01.000 1900-01-01 16:14:02.000 -1
1900-01-01 16:20:01.000 1900-01-01 16:15:01.000 -5

答案 2 :(得分:0)

SELECT CONVERT(VARCHAR(8),
               DATEADD(minute, (DATEDIFF(n, 0, time) / 2) * 2, 0),
               108),
       COUNT(*)
FROM times
GROUP BY DATEDIFF(n, 0, time) / 2

<强>说明: CONVERTDateTime格式显示hh:mm:ss(= 108)。 DATEDIFF转换为分钟然后除以2,舍入为整数,因此每2分钟GROUP解析为相同的整数。 DATEADD用于将此分钟数转换回DateTime,乘以2以返回正确(舍入)时间。

请参阅SQL Fiddle Demo