diff --git a/source/_integrations/sql.markdown b/source/_integrations/sql.markdown index 8eee1da5adaa..342d75f6daed 100644 --- a/source/_integrations/sql.markdown +++ b/source/_integrations/sql.markdown @@ -81,7 +81,7 @@ sql: query: description: An SQL QUERY string, should return 1 result at most. required: true - type: string + type: template column: description: The field name to select. required: true @@ -149,6 +149,7 @@ The `sql.query` action returns a list of rows, where each row is a dictionary of #### Data type conversion The data returned by the database is converted to be compatible with the action response. The following conversions are applied: + - `Decimal` types are converted to floats. - `Date` and `Datetime` objects are converted to ISO 8601 formatted strings. - `bytes` and `bytearray` are converted to a hexadecimal string prefixed with `0x`. @@ -156,9 +157,10 @@ The data returned by the database is converted to be compatible with the action #### Example -Example of calling the `sql.query` action in an automation: +##### Example of calling the `sql.query` action in an automation: {% raw %} + ```yaml action: sql.query data: @@ -178,11 +180,13 @@ data: 3; response_variable: sun_history ``` + {% endraw %} This would return a result similar to this, which will be stored in the `sun_history` variable: {% raw %} + ```yaml result: - state: below_horizon @@ -245,6 +249,48 @@ LIMIT Use `state` as column for value. +### Amount of state changes since using a template + +This example shows the amount of state changes of the sensor `sensor.temperature_in` +using another sensor's state to provide the time window. + +```yaml +sensor: + - platform: random + name: Temperature in + unit_of_measurement: "°C" +``` + +The query will look like this: + +{% raw %} + +```sql +SELECT + count(state) as changes +FROM + ( + SELECT + states.state + FROM + states + WHERE + metadata_id = ( + SELECT + metadata_id + FROM + states_meta + WHERE + entity_id = 'sensor.temperature_in' + ) + AND last_updated_ts >= strftime('%s','{{ states("sensor.datetime_helper") }}') + ) +``` + +{% endraw %} + +Use `changes` as column for value. + ### Previous state of an entity Based on previous example with temperature, the query to get the former state is : @@ -275,6 +321,7 @@ WHERE 1 ); ``` + Use `state` as column for value. ### State of an entity x time ago