这是我面临的问题: 我有一个包含行的大表,我想在近时将它们分组,更具体地说,时间差小于2分钟,例如如下 使用以下输入数据:
预期结果是
16:01:01 2
16:14:02 2
16:20:02 1
答案 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
答案 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
<强>说明:强>
CONVERT
以DateTime
格式显示hh:mm:ss
(= 108)。
DATEDIFF
转换为分钟然后除以2,舍入为整数,因此每2分钟GROUP
解析为相同的整数。
DATEADD
用于将此分钟数转换回DateTime
,乘以2以返回正确(舍入)时间。