I try to get from a database (phpmyadmin) the average humidity of the last X measurements, for example the last 2 measurement points. I use the platform SQL. My SQL code is as follows:
SELECT AVG(s.`state`) FROM states s INNER JOIN (SELECT state_id FROM states WHERE entity_id='sensor.humidity_2' AND state <> 'unavailable' ORDER BY state_id DESC LIMIT 2) x ON x.state_id = s.state_id
The code works well in phpmyadmin, it gives me the average humidity of the last 2 measurements. Every time the sensor gives a registration, the average humidity changes when I enter the code in phpmyadmin.
Now I have put the SQL code in my config file as follows:
sensor:
- platform: sql
queries:
- name: humi_24_uur
query: "SELECT AVG(s.`state`) FROM states s INNER JOIN (SELECT state_id FROM states WHERE entity_id='sensor.humidity_2' AND state <> 'unavailable' ORDER BY state_id DESC LIMIT 2) x ON x.state_id = s.state_id"
column: 'AVG(s.`state`)'
When I ask the average humidity on demand home assistant gives me the following:
sensor.humi_24_uur= 75.5
Seems good, but when I use phpmyadmin to get the average humidity I get a different number (74,5). Also, home assistant continues to indicate that the average humidity is 75.5 and does not update anymore. Also when I restart the hass.
I can’t find my error. Can someone help me