From 691c673ebbc2fbba55cb466d95e9b27de96d9c15 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Mon, 13 Mar 2023 23:04:06 -1000 Subject: [PATCH] Update SQL query examples for schema 40 (#26591) --- source/_integrations/sql.markdown | 69 +++++++++++++++++++++++++++---- 1 file changed, 62 insertions(+), 7 deletions(-) diff --git a/source/_integrations/sql.markdown b/source/_integrations/sql.markdown index c6ad2e3b6f8..7b88c29e33e 100644 --- a/source/_integrations/sql.markdown +++ b/source/_integrations/sql.markdown @@ -35,11 +35,26 @@ To enable it, add the following lines to your `configuration.yaml` file (example sql: - name: Sun state query: > - SELECT * - FROM states - WHERE entity_id = 'sun.sun' - ORDER BY state_id - DESC LIMIT 1; + SELECT + states.state + FROM + states + LEFT JOIN state_attributes ON ( + states.attributes_id = state_attributes.attributes_id + ) + WHERE + metadata_id = ( + SELECT + metadata_id + FROM + states_meta + where + entity_id = 'sun.sun' + ) + ORDER BY + state_id DESC + LIMIT + 1; column: "state" ``` {% endraw %} @@ -117,7 +132,23 @@ sensor: The query will look like this: ```sql -SELECT * FROM states WHERE entity_id = 'sensor.temperature_in' ORDER BY state_id DESC LIMIT 1; +SELECT + states.state +FROM + states +WHERE + metadata_id = ( + SELECT + metadata_id + FROM + states_meta + WHERE + entity_id = 'sensor.temperature_in' + ) +ORDER BY + state_id DESC +LIMIT + 1; ``` Use `state` as column for value. @@ -126,7 +157,31 @@ Use `state` as column for value. Based on previous example with temperature, the query to get the former state is : ```sql -SELECT * FROM (SELECT * FROM states WHERE entity_id = 'sensor.temperature_in' ORDER BY state_id DESC LIMIT 2) two_entity ORDER BY state_id ASC LIMIT 1; +SELECT + states.state +FROM + states +WHERE + state_id = ( + SELECT + states.old_state_id + FROM + states + WHERE + metadata_id = ( + SELECT + metadata_id + FROM + states_meta + WHERE + entity_id = 'sensor.temperature_in' + ) + AND old_state_id IS NOT NULL + ORDER BY + last_updated_ts DESC + LIMIT + 1 + ); ``` Use `state` as column for value.