Add "state x days ago" query (#27028)

Co-authored-by: Franck Nijhof <frenck@frenck.nl>
Co-authored-by: G Johansson <goran.johansson@shiftit.se>
This commit is contained in:
Marquo1 2023-05-29 16:37:17 +02:00 committed by GitHub
parent 35ead242ea
commit a1d311b731
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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 wont necessarily have a value saved exactly 24 hours ago, use “>=” or “<=” to get one of the closest values.
### Database size
#### Postgres