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