使用 having on SQL 查询

Use having on SQL Query

我使用下一个查询来获取内存使用的平均值,但只需要在平均值大于 x 值时获取数据

SELECT AVG(system.memory.actual.used.pct) AS averageMemory from "metricbeat*" where  host.name.keyword='data.storage' HAVING AVG(system.memory.actual.used.pct)>0.3 and "@timestamp" BETWEEN '2021-10-01T00:00:00.000Z' and '2021-10-15T00:00:00.000Z'

并显示下一个错误

Found 1 problem\nline 1:152: Cannot use HAVING filter on non-aggregate [@timestamp]; use WHERE instead"

当使用 WHERE 子句时,像这样

SELECT AVG(system.memory.actual.used.pct) AS averageMemory from "metricbeat*" where  host.name.keyword='data.storage' and averageMemory>0.3 and "@timestamp" BETWEEN '2021-10-01T00:00:00.000Z' and '2021-10-15T00:00:00.000Z'

显示下一个错误

Found 1 problem\nline 1:8: Cannot use WHERE filtering on aggregate function [AVG(system.memory.actual.used.pct)], use HAVING instead

我很困惑。有什么想法吗?

HAVING AVG(system.memory.actual.used.pct)>0.3 是正确的,因为 HAVING 表示对聚合数据的约束,而 WHERE ... averageMemory>0.3 不正确,因为 WHERE 表示记录级别的约束。

出于同样的原因,HAVING @timestamp BETWEEN '2021-10-01T00:00:00.000Z' and '2021-10-15T00:00:00.000Z' 是错误的,因为 @timestamp 不是聚合值而是记录级别的属性。

所以WHERE ... and @timestamp BETWEEN '2021-10-01T00:00:00.000Z HAVING AVG(system.memory.actual.used.pct)>0.3应该是正确的方法。