I have a (hypotetical) device that logs consumption events of its batteries. It has a few slots and daily logs the percentage consumed for the battery in each slot. This is what the data looks like:
CREATE TABLE batteries
(slot integer, day date, percentage integer);
INSERT INTO batteries
(slot, day, percentage)
VALUES
(0, '2020-05-08', 96),
(0, '2020-05-09', 96),
(0, '2020-05-10', 97),
(0, '2020-05-11', 97),
(0, '2020-05-12', 97),
(0, '2020-05-13', null),
(0, '2020-05-14', 95),
(0, '2020-05-15', 96),
(0, '2020-05-16', null),
(0, '2020-05-17', 1),
(0, '2020-05-18', 2),
(1, '2020-05-08', 10),
(1, '2020-05-09', 10),
(1, '2020-05-10', 10);
The log shows that in slot 0, a battery that was almost completely consumed has been replaced on May 13 by another used battery, which was then replaced on May 16 by a new one. The battery in slot 1 always reported 10% usage.
I need to identify each individual battery, the last value it has reported and the first and last dates it has reported such a value. So this is the output I'm trying to get:
slot min_date max_date percentage sequence
------------------------------------------------------
0 '2020-05-10' '2020-05-12' 97 0
0 '2020-05-15' '2020-05-15' 96 1
0 '2020-05-18' '2020-05-18' 2 2
1 '2020-05-08' '2020-05-10' 10 0
Last known value of battery 0 in slot 0 was 97, which it reported from May 10 to May 12;
Last known value of battery 1 in slot 0 was 96, which it reported only on May 15;
Last known value of battery 2 (current) in slot 0 was 2, which it reported only on May 18;
Last known value of battery 0 (current) in slot 1 was 10, which it reported from May 08 to May 10.
My main issue here is how to get the min and max date for each battery without having a battery id. In this example, if I group by slot and percentage to get the dates, I'll get the wrong min date on battery 1 of slot 0, because there was another battery with the same percentage in that slot before.
Is there a way I can get this result on a SQL query, without post-processing?