Test Data Setup:
create table #Data(ID INT IDENTITY PRIMARY KEY CLUSTERED, EventDateTime datetime, Instance int)
insert into #Data(EventDateTime)
values
('2018-10-16T01:37:23.173'),
('2018-10-16T01:37:31.447'),
('2018-10-16T01:37:36.577'),
('2018-10-16T01:37:45.457'),
('2018-10-16T01:37:48.860'),
('2018-10-16T01:38:06.407'),
('2018-10-16T01:38:11.030'),
('2018-10-16T01:38:15.470'),
('2018-10-16T01:38:19.133'),
('2018-10-16T01:38:27.830')
Desired Output (which I can get):
Did this using quirky update:
declare @Instance int = 1
declare @StartDate datetime
select top 1 @StartDate = EventDateTime from #Data order by id asc
update t
set @Instance = Instance = case when ABS(datediff(MILLISECOND,t.EventDateTime, @StartDate)) < 10000 then @Instance else @Instance+1 end
, @StartDate = case when ABS(datediff(MILLISECOND,t.EventDateTime, @StartDate)) < 10000 then @StartDate else EventDateTime end
from #Data t
This is what it's doing in this specific example and it's the logic required:
- Check row 1, if it’s within 10 seconds of @StartDate (Yes) then keep both the @InstanceID and @StartDate the same and set Instance to @InstanceID
- Check row 2, if it’s within 10 seconds of @StartDate (still the original one, so Yes) then keep both the @InstanceID and @StartDate the same and set Instance to @InstanceID
- Check row 3, if it’s within 10 seconds of @StartDate (still the original one, so No) then increment @instanceID by one and set Instance to that, and reset @StartDate to the Transactiondate of this record
- Check row 4, if it’s within 10 seconds of @StartDate (now the one from row 3, so Yes) then keep both the @InstanceID and @StartDate the same and set Instance to @InstanceID
- Check row 5, if it’s within 10 seconds of @StartDate (still the one from row 3, so No) then increment @instanceID by one and set Instance to that, and reset @StartDate to the Transactiondate of this record
- etc
- etc
The Question:
This can be done using a while loop, a cursor, or a quirky update. Is there a truly set based method for doing this (i.e none of the mentioned methods)?
