As reported to my previous question (that for completeness is reported here), I've solved my problem using the window function LAG
to get the time between the previous and next row, sum them and then extract the minutes of production hours of my solar panel system.
The schema of the table is the following one:
+-----------------------------------------------------------------------------------------------------+
| pk,insert_time,data,sensor |
+-----------------------------------------------------------------------------------------------------+
| 3003711,2020-10-03 09:55:54.271738+00,"{""smart_device_id"": 12, ""potenza_kw"": 0, ""temp"": 20.8, ""lux"": 2.0}",12 |
| 3003692,2020-10-03 09:54:54.289131+00,"{""smart_device_id"": 12, ""potenza_kw"": 0, ""temp"": 20.6, ""lux"": 2.0}",12 |
| 3003681,2020-10-03 09:53:54.287502+00,"{""smart_device_id"": 12, ""potenza_kw"": 9.0, ""temp"": 20.5, ""lux"": 2.0}",12 |
| 3003670,2020-10-03 09:52:54.284262+00,"{""smart_device_id"": 12, ""potenza_kw"": 9.0, ""temp"": 20.5, ""lux"": 2.0}",12 |
| 3003659,2020-10-03 09:51:56.382746+00,"{""smart_device_id"": 12, ""potenza_kw"": 12, ""temp"": 20.5, ""lux"": 2.0}",12 |
| 3003648,2020-10-03 09:50:54.279558+00,"{""smart_device_id"": 12, ""potenza_kw"": 9.0, ""temp"": 20.5, ""lux"": 2.0}",12 |
| 3003637,2020-10-03 09:49:56.377988+00,"{""smart_device_id"": 12, ""potenza_kw"": 9.0, ""temp"": 20.5, ""lux"": 2.0}",12 |
+-----------------------------------------------------------------------------------------------------+
Basically, with the following query, I'm able to specify a month and a year and then calculate the total seconds of kW
production, after that, I'll calculate the total hours and days over the cte aggregated table, here is the complete query:
with cte_temp as (
SELECT mt.insert_time,
(DATE_PART('day', lag(mt.insert_time) OVER w - mt.insert_time) * 24 + --Calculates the delta between the two measurements in seconds
DATE_PART('hour', lag(mt.insert_time) OVER w - mt.insert_time)* 60 +
DATE_PART('minute', lag(mt.insert_time) OVER w - mt.insert_time) * 60 +
DATE_PART('second', lag(mt.insert_time) OVER w - mt.insert_time)) as total_seconds
FROM tv_smartdevicemeasurement_mqtt mt
WHERE smart_device_id = 8 -- Filter Section
AND (mt.data->>'potenza_kw')::float > 1
AND date_part('month', mt.insert_time) = 10
AND date_part('year', mt.insert_time) = 2020
WINDOW w AS (order by insert_time desc)
)
SELECT --Calculates total sum of hours and days over temp cte table
TRUNC(sum("total_seconds")::numeric/3600, 2) AS "Hours" --Hours
from cte_temp
I have a lot of issues with this query: i need to repeat this query (on grafana) for all my devices (that are around 15) and it takes a lot of time: producing very high CPU and Memory usage, for completeness, here it's the execution plan with EXPLAIN ANALYZE VERBOSE
Is anyone able to give me some alternative solutions to that?