I’d like to somehow display the average power consumption for each hour of the day over a longer period of time.
With SQL this would be easily done with a GROUP BY -query like this:
SELECT AVG(state), HOUR(FROM_UNIXTIME(last_updated_ts)) FROM hass.states WHERE entity_id = 'sensor.power_total' GROUP BY HOUR(FROM_UNIXTIME(last_updated_ts))
This returns the average power consumption for each hour of the day, which is exactly the data I want, but I haven’t been able to find a card or integration that would visualize this data for me. Apex-charts seemed like the most potential option, but it only supports a timeline based chart.
Statistics-graph card is also not an option, since it doesn’t allow grouping the data by hour.
but this behaves pretty much the same way as apex-chart did and only shows the consumption of the most recent day. If I add more hours to the hours_to_show, it just adds more datapoints to the chart instead of grouping by the hour.
The SQL query example returns data in this format:
I managed to get this working by creating a SQL sensor that returns the average consumption in a single row (separated by commas). Then I parsed the value in an apex-chart.
Now I have a fancy chart that shows me during which hours I use the most energy and which hours are the most expensive in average.
SQL query:
SELECT AVG(state) as total_average, GROUP_CONCAT(state ORDER BY hour) as hourly_averages
FROM (
SELECT ROUND(AVG(state), 0) as state, HOUR(FROM_UNIXTIME(last_updated_ts)) as hour
FROM hass.states
WHERE entity_id = 'sensor.power_total'
GROUP BY HOUR(FROM_UNIXTIME(last_updated_ts))
) t;
Thank you for posting this thread. I also had a similar goal of displaying a chart of my average water usage by hour of the day. I am still using the default Home Assistant sqlite database. I wasn’t able to use FROM_UNIXTIME() and I think my tables or entities are configured slightly different from yours. Using the SQLite Web Add-on helped to troubleshoot my query.
I had to do an additional lookup to get the attributes_id of my sensor from the state_attributes table, since my states table had NULL for all entities_id.
I ended up manually calculating the hours. ( local timezone offset: +54000, convert ts seconds to hours /60/60, mod division to get hour of day %24) I know this will have problems around daylight savings time.
SELECT AVG(state) as total_average, GROUP_CONCAT(state ORDER BY hour) as hourly_averages
FROM (
SELECT ROUND(AVG(state),2) as state, ((last_updated_ts+54000/60/60) %24 ) as hour
FROM "states"
WHERE attributes_id = (SELECT attributes_id FROM "state_attributes" WHERE shared_attrs LIKE "%water_3%")
GROUP BY hour
) t;
I used the SQL integration with hourly_averages as the column