SQL Diff of Whole Date
I am trying to devise a query that will group records by date. I have records that represent events that have occurred. If events occurred on the same section and within 50ms of each oth开发者_StackOverflower, they should be grouped. The important part of my table looks like this:
ID | sectionID | eventDateTime | ...
I am thinking I would want to group by sectionID
and eventDateTime
(a sectionID
will span IDs) and use a having clause to define my time grouping constraints. I also think this might not be possible with a query. I saw DATEDIFF()
, but that only does calculations on a single component of the dates. Any help would be greatly appreciated.
Are you looking for something akin to the following:
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
精彩评论