You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带工作时间过滤的sum by(label) PromQL查询返回异常求助

问题根源

这个问题出在PromQL/VictoriaMetricsQL的and操作标签匹配规则上:

  • sum by(labelname)会生成带指定标签的多个时间序列
  • hour()返回的是无任何标签的单一序列
  • 默认and要求左右两边序列标签完全一致才保留结果,大部分分组序列因标签不匹配被过滤,最后只剩异常的单值结果

解决方法

方法1:用on()忽略标签差异,保留分组结果

通过on()让时间过滤条件对所有分组序列生效,不用考虑标签匹配:

sum by(labelname) (
  rate(runtime_stats_microseconds_total{resource="cpu_time", database_name="main_db"}[5m])
) and on() (hour() >= 6 and hour() <= 18)

对应VictoriaMetricsQL的with写法:

with (
  filter = {resource="cpu_time", database_name="main_db"},
  metric = runtime_stats_microseconds_total{filter},
  current_rate = rate(metric[5m])
)
sum by(labelname) (current_rate) and on() (hour() >=6 <=18)

方法2:乘法嵌入过滤(非工作时间返回0)

如果接受非工作时间返回0值而非完全无数据,直接用布尔条件相乘:

sum by(labelname) (
  rate(runtime_stats_microseconds_total{resource="cpu_time", database_name="main_db"}[5m])
  * (hour() >= 6 and hour() <= 18)
)

方法3:子查询嵌套过滤

把时间过滤嵌到sum by的子查询里,逻辑更直观:

sum by(labelname) (
  rate(runtime_stats_microseconds_total{resource="cpu_time", database_name="main_db"}[5m])
  and hour() >=6 <=18
)

这些方法都能同时保证标签分组正常和时间过滤有效,不属于查询语言限制,只是要正确利用标签匹配规则。

内容的提问来源于stack exchange,提问作者NielsK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.11 12:43:11