我正在尝试设计一个按日期对记录进行分组的查询。我有记录代表已发生的事件。如果事件发生在同一部分并且相互之间的距离不超过50毫秒,则应将它们分组。我表格的重要部分如下:
ID | sectionID | eventDateTime | ...
我想我想要按sectionID
和eventDateTime
分组(sectionID
将跨越ID)并使用having子句来定义我的时间分组约束。我也认为查询可能无法做到这一点。我看到DATEDIFF()
,但只对日期的单个组件进行计算。任何帮助将不胜感激。
答案 0 :(得分:0)
您是否正在寻找类似于以下内容的内容:
With [Events] As
(
Select 1 As Id, 5 As SectionId, Cast('2011-05-04 23:59:59.950' As DateTime) As EventDateTime
Union All Select 2, 5, '2011-05-05 00:00:00.000'
Union All Select 3, 5, '2011-05-05 00:00:00.049'
)
, TaggedData As
(
Select E1.Id, E1.sectionID
, Cast(Coalesce(E2.EventDateTime, E1.EventDateTime) As Date) As TagEventDateTime
From [Events] As E1
Left Join [Events] As E2
ON E2.sectionID = E1.sectionID
And E2.Id <> E1.Id
And E2.EventDateTime >= DateAdd(ms, -50, E1.EventDateTime)
And E2.EventDateTime <= E1.EventDateTime
)
Select SectionId, TagEventDateTime
From TaggedData
Group By SectionId, TagEventDateTime