count(count by (a) (hello_info))

First you want an aggregator with a result per value of a, and then you can count them.

Answer from brian-brazil on Stack Overflow
🌐
OpenObserve
openobserve.ai › home › blog › prometheus metrics count basics
Prometheus Metrics Count Basics
September 26, 2025 - Learn how Prometheus metrics counts unique label values using basic queries and methods like `count(count by (label) (metric))`.
Discussions

promql - Prometheus count specific value occurrences - Stack Overflow
Can someone please help me to solve the task by counting a gauge value? I have one metric but it always has different device labels, and it can only be 1 or 0, where 1 = error and 0 = OK. I need to More on stackoverflow.com
🌐 stackoverflow.com
How to calculate the number of requests in a time period using PromQL
Hello, community! I am building a dashboard in Grafana to monitor the latency and the number of requests made to a specific API. The metrics are being collected via Google Cloud Managed Service for Prometheus and accessed in Grafana using Google Cloud Monitoring as the data source. More on community.grafana.com
🌐 community.grafana.com
4
0
November 21, 2024
count - PromQL: Counting samples of a time series - Stack Overflow
Just use count_over_time function. For example, the following query returns the number of raw samples over the last 2 minutes per each time series with the name instana_metrics: ... Note that Prometheus calculates the provided query independently per each point on the graph, e.g. More on stackoverflow.com
🌐 stackoverflow.com
Calculating the Avg with Gaps in Data
I've had to do this for work multiple times and Prometheus isn't the correct tool unfortunately. It isn't made to store high cardinality fields like IP addresses. As you're using sFlow, this is more log-based and OLAP databases are more appropriate. But trying to answer your question: avg_over_time((sflow_asn_bps OR on() vector(0) )[10h]) and taking the instant value (haven't tested it but you'd complete the timeseries with zero values then doing the average) would summing sum_over_time and dividing by 10 hours work? More on reddit.com
🌐 r/PrometheusMonitoring
4
2
November 29, 2024
Top answer
1 of 2
3

I came up with two solutions to this, choose whichever suits you best. For the purpose of simplifying things, let's assume your Prometheus scrape at 15 seconds interval and the error state lasted for 1 minute. Then, the gathered data would look like this:

state_metric 0 @t
state_metric 1 @t+15s
state_metric 1 @t+30s
state_metric 1 @t+45s
state_metric 1 @t+60s
state_metric 0 @t+75s

With changes()

This shows how many state changes were there. It would return 1 for the exemplary data above and it only gives adequate results if the gauge in question can hold exactly two possible values (for example 1 and 0).

changes(state_metric[1d])/2

changes() shows how many times the metric value has changed during the interval, while division by 2 is to compensate the state change back to normal. This is the downside of this method, which makes it only usable for detecting quick changes of state. But you probably have an alert when the error state hangs for some time, so I think this shouldn't be really a problem.

With a subquery

This is more precisely what you asked:

the number of times when metrics were 1

But there is a catch: with the exemplary data above, the query below will return you 4:

sum_over_time(count(state_metric == 1)[1d:])

[1d:] means repeat that instant query (count(state_metric == 1)) for each data point during last 1d. This is precisely the number of times when state_metric was 1 and it can be useful, for example, to calculate the downtime (just multiply by the scrape interval). Unlike the first method, this can work with any number of possible states, since you can define what you need in the condition.

2 of 2
1

I need to calculate the number of times when metrics were 1 by range variable provided in Grafana.

The following query should return the number of times the time series matching aqa_device_health_checker{env="dev", device="FOO"} series selector had value 1 on the selected time range in Grafana (aka $__range):

last_over_time(
  sum_over_time(
    aqa_device_health_checker{env="dev", device="FOO"}[$__range] offset -$__range
  )[$__range:$__range]
)

The query returns individual results per each matching time series. If you need summary result over all the matching time series, then just wrap the query above into sum():

sum(
  last_over_time(
    sum_over_time(
      aqa_device_health_checker{env="dev", device="FOO"}[$__range] offset -$__range
    )[$__range:$__range]
  )
)

Note that both queries above allow calculating the number of times the metric had 1 value if the metric could have either 0 or 1 values. If the metric can have other values, then these queries won't work as expected. Unfortunately, Prometheus doesn't provide easy to use functionality for counting the number of raw samples with some pre-defined value N. If you know beforehand the interval between samples (aka scrape_interval), then the following hack based on Prometheus subquery can be used:

count_over_time(
  (
    last_over_time(m[scrape_interval]) == N
  )[$__range:scrape_interval]
)

This query counts the number of raw samples with values equal to N on the time range $__range selected in Grafana.

If the interval between samples isn't known beforehand, then it is impossible to calculate the number of samples with a particular value in Prometheus. If you still need this functionality, then take a look at count_eq_over_time() function provided by VictoriaMetrics - this is Prometheus-like monitoring solution I work on. For example, the following query returns the exact number of samples with the value 10 over the last hour for time series m:

count_eq_over_time(m[1h], 10)
🌐
client_python
prometheus.github.io › client_python › instrumenting › counter
Counter | client_python
April 9, 2026 - A Counter tracks a value that only ever goes up. Use it for things you count — requests served, errors raised, bytes sent. When the process restarts, the counter resets to zero. If your value can go down, use a Gauge instead. from prometheus_client import Counter c = Counter('my_failures', 'Description of counter') c.inc() # Increment by 1 c.inc(1.6) # Increment by given value If there is a suffix of _total on the metric name, it will be removed.
🌐
Prometheus
prometheus.io › docs › prometheus › latest › querying › operators
Operators | Prometheus
For /, the histogram sample has to be on the left hand side (LHS), followed by the scalar on the right hand side (RHS). All bucket populations and the count and the sum of observations are then divided by the scalar.
🌐
Better Stack
betterstack.com › community › questions › prometheus-to-count-unique-label-values
Prometheus Query to Count Unique Label Values | Better Stack Community
December 2, 2024 - If you want to get the distinct unique values of a label (rather than just counting how many times each unique value appears), you can use the count function on the label_replace function. Here’s an example: ... This will give you the count of requests grouped by the status code. ... Get notified with a radically better infrastructure monitoring platform. Explore more ... This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. ... Prometheus counters are metrics that only increase or reset to zero.
🌐
HexDocs
hexdocs.pm › prometheus_ex › Prometheus.Metric.Counter.html
Prometheus.Metric.Counter — Prometheus.ex v5.1.0
Increments the counter identified by spec by value. Raises Prometheus.InvalidValueError exception if value isn't a positive number.<br> Raises Prometheus.UnknownMetricError exception if a counter for spec can't be found.<br> Raises Prometheus.InvalidMetricArityError exception if labels count mismatch.
Find elsewhere
🌐
Prometheus
prometheus.io › docs › prometheus › latest › querying › functions
Query functions | Prometheus
Use rate for alerts and slow-moving counters, as brief changes in the rate can reset the FOR clause and graphs consisting entirely of rare spikes are hard to read. Note that when combining irate() with an aggregation operator (e.g. sum()) or a function aggregating over time (any function ending in _over_time), always take an irate() first, then aggregate.
🌐
OneUptime
oneuptime.com › home › blog › how to count unique label values in prometheus
How to Count Unique Label Values in Prometheus
December 17, 2025 - However, understanding how many unique values exist for a given label is crucial for cardinality management and query optimization. This guide shows you how to count unique label values using PromQL. Use count(group by (label_name) (metric_name)) to ...
🌐
GitConnected
levelup.gitconnected.com › prometheus-counter-metrics-d6c393d86076
Working With Prometheus Counter Metrics | Level Up Coding
February 28, 2022 - We should only use Irate with counters. Prometheus’ resets function gives you the number of counter resets over a specified time window². The following PromQL expression calculates the number of job execution counter resets over the past 5 minutes.
🌐
Grafana
community.grafana.com › t › how-to-calculate-the-number-of-requests-in-a-time-period-using-promql › 136815
How to calculate the number of requests in a time period using PromQL - Grafana - Grafana Labs Community Forums
November 21, 2024 - Hello, community! I am building a dashboard in Grafana to monitor the latency and the number of requests made to a specific API. The metrics are being collected via Google Cloud Managed Service for Prometheus and access…
🌐
Medium
pramodshehan.medium.com › prometheus-counter-metrics-1b0a4cbb79e1
Prometheus Counter metrics. There are three functions to calculate… | by Pramod Shehan | Medium
January 18, 2026 - We can calculate the actual increase by adding the counter value before the reset to the new counter value after the reset (see Figure 02). In Prometheus, this is handled more efficiently internally and does not require generating a full list of corrected samples. After a reset, the calculated values may not be exact, since some increments can be lost during the reset (for example, just before a service restart). previous value before reset + lower value after reset ... When calculating the rate, increase function in Prometheus, we need to know only first and last value of the counter under the time window.
🌐
Last9
last9.io › blog › prometheus-functions
Prometheus Functions: How to Make the Most of Your Metrics | Last9
February 28, 2025 - Prometheus excels at data aggregation using functions like: sum, avg, min, max, count – Aggregate metrics across different dimensions.
🌐
OneUptime
oneuptime.com › home › blog › how to calculate cumulative increase in prometheus
How to Calculate Cumulative Increase in Prometheus
December 17, 2025 - Calculating cumulative increase in Prometheus requires understanding how counters work and using increase() appropriately. For dashboards showing totals, use increase() with suitable time ranges. For historical analysis, combine with recording rules to maintain long-term aggregates.
🌐
SigNoz
signoz.io › guides › how to count unique label values with prometheus queries
How to Count Unique Label Values with Prometheus Queries | SigNoz
September 6, 2024 - Be mindful of this to avoid overwhelming your Prometheus server. Misleading Aggregations: Ensure your by() clauses make logical sense to avoid misleading aggregations. Double-check that the labels used align with your intended analysis. The count_values() function offers an alternative approach to counting unique label values:
🌐
MetricFire
metricfire.com › blog › what-are-prometheus-functions
What are Prometheus Functions? | MetricFire
June 25, 2024 - As another example, you can use the increase() Prometheus function to count the number of HTTP requests over the past 5 minutes, e.g.:
🌐
Google Groups
groups.google.com › g › prometheus-users › c › QsY_OkdH_gU
number of occurrences in a day
The only way I know to get an exact answer is to send the range vector query "foo[24h]" to the *instant* query endpoint, then filter and count the samples client-side. A range vector like that gives the raw values with their raw timestamps as stored in the TSDB. For this use case it would be nice if Prometheus were to allow certain operators to work directly on range vectors, so you could write
🌐
Google Groups
groups.google.com › g › prometheus-developers › c › GLhJEubuRaE
Counting events over arbitrary time intervals
For Prometheus we do some extrapolation, which uses the points in a bucket to estimate out to the boundaries of the bucket. Namely, how do I aggregate counters into larger time intervals based on monotonically increasing counter metric? I might be oversimplifying things but it looks like if there was a function that takes a diff between t and t-1 datapoints (accounting for counter resets of course) then I would "sum_over_time" results of this function to get desired result.