I have a table of events, I need to find all tail events of type 1 and all head events of type 1.
So, for the set of events in this order [1, 1], 3, 1 ,4, 5, [1,1,1] the brackets denote head and tail events of type 1.
This is much better illustrated in SQL:
drop table #event
go
create table #event (group_id int, [date] datetime, [type] int)
create index idx1 on #event (group_id, date)
insert into #event values (1, '2000-01-01', 1)
insert into #event values (1, '2000-01-02', 1)
insert into #event values (1, '2000-01-03', 3)
insert into #event values (1, '2000-01-04', 2)
insert into #event values (1, '2000-01-05', 1)
insert into #event values (2, '2000-01-01', 2)
insert into #event values (2, '2000-01-02', 2)
insert into #event values (2, '2000-01-03', 3)
insert into #event values (2, '2000-01-04', 2)
insert into #event values (2, '2000-01-05', 1)
insert into #event values (3, '2000-01-01', 1)
insert into #event values (3, '2000-01-02', 2)
insert into #event values (3, '2000-01-03', 1)
insert into #event values (3, '2000-01-04', 2)
insert into #event values (3, '2000-01-05', 2)
insert into #event values (4, '2000-01-01', 2)
insert into #event values (4, '2000-01-02', 2)
insert into #event values (4, '2000-01-03', 3)
insert into #event values (4, '2000-01-04', 1)
insert into #event values (4, '2000-01-05', 1)
go
select e1.* from #event e1
where (
not exists (
select top 1 1
from #event e2
where e1.group_id = e2.group_id
and e2.date < e1.date
and e2.type <> 1
) or not exists (
select top 1 1
from #event e2
where e1.group_id = e2.group_id
and e2.date > e1.date
and e2.type <> 1
)
)
and e1.type = 1
Expected results:
1 2000-01-01 00:00:00.000 1
1 2000-01-02 00:00:00.000 1
1 2000-01-05 00:00:00.000 1
2 2000-01-05 00:00:00.000 1
3 2000-01-01 00:00:00.000 1
4 2000-01-04 00:00:00.000 1
4 2000-01-05 00:00:00.000 1
This all works just fine and returns my expected results, but it scans through the table 3 times. Is there any way to make this perform faster and reduce the number of table scans?