用于Grafana的InfluxDB查询:获取字段不同值的计数
Got it, let's walk through how to write the right InfluxDB queries for Grafana to count distinct values (and their occurrences) in your three fields. I'll cover common use cases you'll likely need:
If you just want the total number of distinct values in a field across your selected time range, use these queries (replace your_measurement_name with your actual InfluxDB measurement name):
For FieldA
SELECT COUNT(DISTINCT("FieldA")) AS "Unique FieldA Values" FROM "your_measurement_name" WHERE $timeFilter
For FieldB
SELECT COUNT(DISTINCT("FieldB")) AS "Unique FieldB Values" FROM "your_measurement_name" WHERE $timeFilter
For FieldC
SELECT COUNT(DISTINCT("FieldC")) AS "Unique FieldC Values" FROM "your_measurement_name" WHERE $timeFilter
The $timeFilter is a Grafana built-in variable that automatically uses the time range selected on your dashboard—super handy for filtering without hardcoding dates.
If you want to see how many times each individual value appears (e.g., how many entries have FieldA = "A", FieldA = "B", etc.), use GROUP BY on the field:
For FieldA (count per value)
SELECT COUNT("FieldA") AS "Occurrences" FROM "your_measurement_name" WHERE $timeFilter GROUP BY "FieldA"
For FieldB (count per value)
SELECT COUNT("FieldB") AS "Occurrences" FROM "your_measurement_name" WHERE $timeFilter GROUP BY "FieldB"
For FieldC (count per value)
SELECT COUNT("FieldC") AS "Occurrences" FROM "your_measurement_name" WHERE $timeFilter GROUP BY "FieldC"
This will return a list of each unique value in the field paired with how many times it shows up. Perfect for bar charts or pie graphs in Grafana.
If you want to track how the number of unique values changes over time (e.g., hourly), add a time-based GROUP BY:
Example: Hourly unique FieldA values
SELECT COUNT(DISTINCT("FieldA")) AS "Hourly Unique FieldA" FROM "your_measurement_name" WHERE $timeFilter GROUP BY time(1h)
Adjust time(1h) to whatever interval you need—1m for minute, 1d for day, etc.
- Use a Stat Panel if you just want to display the total unique count as a big number.
- Use a Bar Chart or Pie Chart for the per-value occurrence counts to visualize distribution.
- Double-check that your fields are stored as the right type in InfluxDB: if FieldB is meant to be a string (like "00", "02"), make sure it's not stored as a numeric field—otherwise
GROUP BYmight behave unexpectedly.
内容的提问来源于stack exchange,提问作者Atmesh Mishra

