… and this is what I came up with. Still a little rough on the edges.
@Miguel61 ;
PROBLEM
We have consecutive (1,2,3) triple records scattered in the table.
Find them.
STEPS
- Find and narrow down consecutive (1,3) couple records
To narrow down the record set for this couple of records, we use this info:
- Eliminate unfitted (1,3) couple records
The approach is to eliminate:
-
those that don’t have a (2) record between them:
f.description = ‘RETURN AAABBB’ and (f.id > e.maxa and f.id < e.maxb)
-
those that have one other record between them:
and not exists (select g.id from test g where g.id != f.id and (g.id > e.maxa and g.id < e.maxb))
CODE
Test table
create table test (id int, description varchar(50));
INSERT INTO test VALUES (1, 'OPEN-AAA FSN');
INSERT INTO test VALUES (3, 'OPEN-AAA FSN');
INSERT INTO test VALUES (4, 'RETURN AAABBB');
INSERT INTO test VALUES (5, 'RETURN AAABBB');
INSERT INTO test VALUES (6, 'REMOTE POSITIVE CH SN AAAA');
INSERT INTO test VALUES (10, 'REMOTE POSITIVE CH SN AAAA');
INSERT INTO test VALUES (11, 'REMOTE POSITIVE CH SN AAAA');
INSERT INTO test VALUES (14, 'OPEN-AAA FSN');
INSERT INTO test VALUES (16, 'REMOTE POSITIVE CH SN AAAA');
INSERT INTO test VALUES (20, 'OPEN-AAA FSN');
INSERT INTO test VALUES (21, 'REMOTE POSITIVE CH SN AAAA');
INSERT INTO test VALUES (22, 'OPEN-AAA FSN');
INSERT INTO test VALUES (34, 'RETURN AAABBB');
INSERT INTO test VALUES (86, 'REMOTE POSITIVE CH SN AAAA');
INSERT INTO test VALUES (93, 'OPEN-AAA FSN');
INSERT INTO test VALUES (102, 'REMOTE POSITIVE CH SN AAAA');
INSERT INTO test VALUES (225, 'RETURN AAABBB');
INSERT INTO test VALUES (452, 'REMOTE POSITIVE CH SN AAAA');
INSERT INTO test VALUES (800, 'RETURN AAABBB');
SQL Query
select e.maxa,
f.id,
e.maxb
from
(
select c.maxa,
c.maxb
from
(
select max(a.id) maxa,
b.id maxb
from
(
select id
from test
where description = 'OPEN-AAA FSN'
)
a,
(
select id
from test
where description = 'REMOTE POSITIVE CH SN AAAA'
)
b
where a.id <= b.id - 2
group by b.id
) c
inner join
(
select a.id mina,
min(b.id) minb
from
(
select id
from test
where description = 'OPEN-AAA FSN'
)
a,
(
select id
from test
where description = 'REMOTE POSITIVE CH SN AAAA'
)
b
where a.id <= b.id - 2
group by a.id
order by a.id asc
) d
on c.maxa = d.mina and c.maxb = d.minb
) e,
test f
where f.description = 'RETURN AAABBB'
and (f.id > e.maxa and f.id < e.maxb)
and not exists (select g.id from test g where g.id != f.id and (g.id > e.maxa and g.id < e.maxb))