2

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

  • 16:01:01
  • 乙 16:01:20
  • 16:14:02
  • 16:15:01
  • 16:20:02

预期的结果是

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

3 回答 3

1

如果您使用的是 SQL Server 2012,那么您很幸运,您可以使用lagfunction 和 rolling total 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 小提琴演示

于 2013-08-18T13:14:38.350 回答
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
于 2013-08-18T13:11:56.860 回答
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

说明: CONVERT显示格式(= 108) DateTime。转换为分钟,然后除以 2,四舍五入为整数,因此2 分钟中的每一分钟都解析为相同的整数。 用于将此分钟数转换回 a ,乘以 2 以返回正确的(四舍五入)时间。hh:mm:ssDATEDIFFGROUPDATEADDDateTime

请参阅SQL Fiddle 演示

于 2013-08-18T13:17:22.097 回答