InfluxDB中统计Measurement数据分组计数的正确语法求助
Fixing InfluxDB Count & Group By for Your Measurement
Hey there! Let's get that count-by-value query working for you. Your initial approach of using COUNT(*) with GROUP BY is on the right track—you just need to tweak the syntax to match InfluxQL's requirements, and add a few touches to get the exact output format you want.
The Correct InfluxQL Query
Here's the query that will give you the count of results per foo value:
SELECT COUNT(*) AS numResults FROM myMeasurement GROUP BY "foo"
Breaking Down Why This Works
COUNT(*): This counts every data point in each group, which is exactly what you need to tally how many times eachfoovalue appears.AS numResults: Renames the count column to match thenumResultsname you want in your output.GROUP BY "foo": Groups your data by the distinct values in thefoofield. Wrappingfooin double quotes is a safe practice in InfluxQL—it avoids conflicts with keywords and ensures the field name is interpreted correctly.
What the Output Will Look Like
When you run this query, InfluxDB will return results grouped by each foo value (formatted as series with tags):
name: myMeasurement tags: foo=valOne time numResults ---- ---------- 1970-01-01T00:00:00Z 3 name: myMeasurement tags: foo=valTwo time numResults ---- ---------- 1970-01-01T00:00:00Z 2 name: myMeasurement tags: foo=valThree time numResults ---- ---------- 1970-01-01T00:00:00Z 4
If You Want a Compact Table Format (InfluxDB 2.x+)
If you're using InfluxDB 2.x, Flux (the newer query language) can return results in the exact tabular format you showed. Here's the Flux query:
from(bucket: "your-bucket-name") |> range(start: 0) // Adjust start time if you don't want all historical data |> filter(fn: (r) => r._measurement == "myMeasurement" and r._field == "foo") |> group(columns: ["_value"]) |> count(column: "_value") |> rename(columns: {_value: "foo", count: "numResults"}) |> keep(columns: ["foo", "numResults"])
This will output:
foo numResults --- ---------- valOne 3 valTwo 2 valThree 4
内容的提问来源于stack exchange,提问作者ekjcfn3902039




