To transform string values like "off", "cool", "warm" into integers for visualization purposes in Grafana, you'll have to map the string values to integers in your InfluxDB query or Grafana panel, since InfluxQL doesn’t support native case/if logic or value transformation like SQL-style CASE statements.
Here are a few options depending on your exact setup:
✅ Best Approach (via Grafana Value Mapping)
Since InfluxQL does not support transforming strings to integers in the query itself, Grafana's value mapping is the recommended solution:
-
Keep using your original query:
SELECT last("state") FROM "units" WHERE ("entity_id"::tag =~ /^$Habitaciones$/) AND $timeFilter GROUP BY time($__interval), "entity_id"::tag, "domain"::tag, "domain"::tag fill(previous)
-
In Grafana, go to your panel settings:
- Open the Field tab.
- Under Value Mappings, define mappings like:
"off" → 0
"cool" → 1
"warm" → 2
null (or empty) → map to a default (e.g., -1 or N/A)
This way, your panel can treat the states as integers for graphing or gauges, even though the underlying data in InfluxDB is still a string.
⚠️ Alternative (via Data Preprocessing or Replication)
If you're ingesting this data yourself or can control how it’s written to InfluxDB, you might consider writing both the original and a numeric version:
"state" = "cool"
"state_code" = 1 ← numerical version for graphing
Then you can simply query:
SELECT last("state_code") FROM ...
But this requires modification of your data ingestion process (Home Assistant automation, Node-RED, custom script, etc.).
🚫 InfluxQL Limitations
Unfortunately, InfluxQL:
- ❌ Does not support CASE, IF, or inline value mappings
- ❌ Cannot dynamically convert strings to integers
- ✅ Only returns raw field values or aggregates
So mapping must happen outside the Influx query.
✅ Summary
| Solution | Description | Effort |
|---|
| Grafana value mapping (recommended) | Map "cool" → 1 etc. in visualization | ⭐ Super easy |
| Modify ingestion | Add parallel state_code field | 🛠 Medium |
| Use Flux (if supported) | If your InfluxDB version supports Flux, more powerful logic is available | ❗Advanced |
Let me know if you're using Flux, and I can help convert the query there — it supports map, if, case-like logic.