The following query finds all subsequent intervals:
select item1.name, item1.createdDate, item2.createdDate
from mytable item1
join mytable item2
on item1.name = item2.name and
not exists (
select 1
from mytable inneritem
where inneritem.name <> item1.name and
inneritem between item1.createdDate and item2.createdDate
);
however, the query above will yield subsets of longer intervals as separate sets, so, in order to restrict the too broad results of the query above, we need to check the following for each possible pair:
- their name matches
- the first is earlier than the second
- there is no item between the first and the second that does not match their name
- there is no item before the first, matching its name without another item with a different name between them
- there is no item after the second, matching its name without another item with a different name between them
Solution
create table mytable(name varchar(32), createdDate varchar(64));
insert into mytable(name, createdDate) values
('John', '20160101 20:36:12'),
('Max', '20160101 20:36:12'),
('Max', '20160101 20:37:12'),
('Max', '20160101 20:38:12'),
('John', '20160101 20:38:12'),
('John', '20160101 20:39:12'),
('Max', '20160101 20:41:12');
select item1.name, item1.createdDate, item2.createdDate
from mytable item1
join mytable item2
on item1.name = item2.name and
item1.createdDate < item2.createdDate and
not exists (
select 1
from mytable inneritem
where inneritem.name <> item1.name and
inneritem.createdDate > item1.createdDate and
inneritem.createdDate < item2.createdDate
) and
not exists (
select 1
from mytable inneritem
where inneritem.name = item1.name and
inneritem.createdDate < item1.createdDate and
not exists (
select 1
from mytable innerinneritem
where innerinneritem.name <> item1.name and
innerinneritem.createdDate > inneritem.createdDate and
innerinneritem.createdDate < item1.createdDate
)
) and
not exists (
select 1
from mytable inneritem
where inneritem.name = item1.name and
inneritem.createdDate > item2.createdDate and
not exists (
select 1
from mytable innerinneritem
where innerinneritem.name <> item1.name and
innerinneritem.createdDate > item2.createdDate and
innerinneritem.createdDate < inneritem.createdDate
)
);
Fiddle where you can test: http://sqlfiddle.com/#!18/7659f/7
Note
You have duplicate dates with different names, which may cause confusion.