I have an energy counter (kWh) recorded in a MySQL database every 15 minutes.
Sometimes the recording fails for several reasons (power outage, computer reboot for updates…) and values are missing.
The table looks as followed:
id Time Energy
27800 13.02.2024 23:30:01 651720048
27801 13.02.2024 23:45:00 651720672
(missing)
27802 14.02.2024 00:15:02 651721917
27803 14.02.2024 00:30:00 651722540
27804 14.02.2024 00:45:00 651723129
27805 14.02.2024 01:00:02 651723769
27806 14.02.2024 01:15:01 651724405
27807 14.02.2024 01:30:01 651725030
(missing)
27808 14.02.2024 02:00:01 651726275
27809 14.02.2024 02:15:02 651726880
27810 14.02.2024 02:30:01 651727519
27811 14.02.2024 02:45:00 651728130
27812 14.02.2024 03:00:02 651728751
27813 14.02.2024 03:15:02 651729381
I am looking for a SQL query which returns the consumption (spread/difference between energy counter values) in a certain (variable) time span (eg. 15 minutes, 60 minutes, 24 hours, 1 month…) which also considers missing values by interpolation.
The result should look as showed there in the columns Consumption 15m
and Consumption 1h
:
id Time Energy Consumption 15m Consumption 1h
27800 13.02.2024 23:30:01 651720048 -
27801 13.02.2024 23:45:00 651720672 624
(missing) 651721294.5 622.5 -
27802 14.02.2024 00:15:02 651721917 622.5
27803 14.02.2024 00:30:00 651722540 623
27804 14.02.2024 00:45:00 651723129 589
27805 14.02.2024 01:00:02 651723769 640 2474,5
27806 14.02.2024 01:15:01 651724405 636
27807 14.02.2024 01:30:01 651725030 625
(missing) 651725652.5 622.5
27808 14.02.2024 02:00:01 651726275 622.5 2506
27809 14.02.2024 02:15:02 651726880 605
27810 14.02.2024 02:30:01 651727519 639
27811 14.02.2024 02:45:00 651728130 611
27812 14.02.2024 03:00:02 651728751 621 2476
27813 14.02.2024 03:15:02 651729381 630
I guess it is somewhow required to find the closest two values of two given time points (e.g. 14.02.2024 00:00:00 and 14.02.2024 01:00:00) and create an interpolated value of the energy counter to build then the difference of it.
Which query could achieve that desired result?
2
Answers
One option is to generate all 15 minutes intervals between your start and end time – JOIN intervals to your table data filling up the missing rows – approximate the missing consumption and populate missing rows…
Create CTE (named it intervals) to generate all 15 minutes intervals…
… join intervals to your table data doing approximations (where needed) an populate missing rows and to prepare data to calculate consumptions for last 15 min / 1 hour
See example.
Recursive add missing rows with interpolated time and energy.
For test data
Output is
Fiddle