From a1d311b731f13a9f4c7ac325dca1ecb277894cae Mon Sep 17 00:00:00 2001 From: Marquo1 <97259078+Marquo1@users.noreply.github.com> Date: Mon, 29 May 2023 16:37:17 +0200 Subject: [PATCH] Add "state x days ago" query (#27028) Co-authored-by: Franck Nijhof Co-authored-by: G Johansson --- source/_integrations/sql.markdown | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/source/_integrations/sql.markdown b/source/_integrations/sql.markdown index 043d920a58e..7e9fb8656b8 100644 --- a/source/_integrations/sql.markdown +++ b/source/_integrations/sql.markdown @@ -186,6 +186,31 @@ WHERE ``` Use `state` as column for value. +### State of an entity x time ago + +If you want to extract the state of an entity from a day, hour, or minute ago, the query is: + +```sql +SELECT + states.state +FROM + states + INNER JOIN states_meta ON + states.metadata_id = states_meta.metadata_id +WHERE + states_meta.entity_id = 'sensor.temperature_in' + AND last_updated_ts <= strftime('%s', 'now', '-1 day') +ORDER BY + last_updated_ts DESC +LIMIT + 1; +``` + +Replace `-1 day` with the target offset, for example, `-1 hour`. +Use `state` as column for value. + +Keep in mind that, depending on the update frequency of your sensor and other factors, this may not be a 100% accurate reflection of the actual situation you are measuring. Since your database won’t necessarily have a value saved exactly 24 hours ago, use “>=” or “<=” to get one of the closest values. + ### Database size #### Postgres