I have an table and rows like below minimum sample. I want smarter way that can get expected results. Does anyone have any good idea?
create table foo (
id int,
s datetime,
e datetime,
value float
);
insert foo values
(1, '2019-1-1 1:00:00', '2019-1-1 3:00:00', 10.0),
(1, '2019-1-1 1:30:00', '2019-1-1 3:00:00', 10.0),
(1, '2019-1-1 4:00:00', '2019-1-1 5:00:00', 10.0),
(1, '2019-1-1 4:30:00', '2019-1-1 6:00:00', 10.0),
(2, '2019-1-1 2:00:00', '2019-1-1 6:00:00', 15.0),
(2, '2019-1-1 2:00:00', '2019-1-1 6:00:00', 10.0);
I want results such like this.
1, '2019-1-1 1:00:00', '2019-1-1 3:00:00', 10.0
1, '2019-1-1 4:00:00', '2019-1-1 6:00:00', 10.0
2, '2019-1-1 2:00:00', '2019-1-1 6:00:00', 15.0
They have the longer period, merged s and e that is going to be longer period, and larger value than the rows that have overlapping periods.
Additional Information
I thought that the "smart way" is more easy to understand (e.g. less sub-queries is better maybe) and more faster to execute.
Actually, I have an additional geography Point column to "foo" table in sample code, and I have to elect a Point from a row that have lowest "value" in the same time period group. I've thought my logic once. I have no idea to get result without many sub-queries or cursor. So I wanted make my issue more simple to get some idea for this case.