我无法理解如何在以下场景中使用AVG功能,
我有一个名为
requests
的表,它有列 app_name
(字符串)、operation_status
(整数状态代码,如 200、500 等)、timestamp
(整数,这是毫秒时间戳)、 correlated_id
(STRING,这是一个 UUID)。
例如,如果我有以下记录:
INSERT INTO `requests`
(app_name, operation_status, timestamp, correlated_id)
VALUES
("APP_1", 200, 1714207107972, '82156a64-e43f-467f-894d-bf28dc007e2b'),
("APP_1", 500, 1714207107972, '51345b32-a21d-215c-432a-bc13dc115e1c'),
("APP_2", 200, 1714207107972, '41123n43-b15d-134a-673e-ad13ab104a1c'),
("APP_2", 500, 1714207107972, '63246a54-a32g-324c-673e-ad13ab104a1c'),
("APP_3", 200, 1714207107972, '51135b32-b13a-213f-532f-zc09dg213k0h');
我想要一个查询来告诉我每个应用程序发生的 200 个请求的平均数量,因此为此我尝试了以下查询:
SELECT
app_name,
COUNTIF(operation_status = 200) AS successful_ops,
COUNTIF(operation_status = 500) AS failed_ops,
AVG(CASE WHEN operation_status = 200 THEN operation_status END) AS avg_status_200, -- this is not working
(COUNTIF(operation_status=200)/COUNT(operation_status)) AS average_manual -- this is giving me the correct result but I think AVG function should be able to give me this too
FROM
`requests`
GROUP BY
app_name;
例如,APP_1 的正确值是 0.5,因为它有 2 个请求,但只有 1 个是 200,所以 1/2 = 0.5,这是我在查询中使用“average_manual”得到的结果,但我认为
AVG
函数也应该能够给我这个结果,但我不知道正确的方法,感谢任何帮助
平均值计算的官方定义是:
所有观测值的总和除以观测值总数
所以基本上,在你的例子中,你正在做的是:
您要计算的是响应代码为 200 的请求占该应用程序的所有请求的比例。
这就是为什么使用 AVG 方法对您不起作用 - 因为您在计算中使用响应代码作为数字,而不是“指标”。
有多种方法可以实现您所需的结果,其中之一就是您给出的示例,写为“平均手册”。
另一种选择是将 AVG 函数与 CASE 语句结合使用,如下所示:
SELECT
app_name,
COUNTIF(operation_status = 200) as successful_ops,
COUNTIF(operation_status = 500) as failed_ops,
AVG(CASE operation_status WHEN 200 THEN 1 ELSE 0 END) successful_ops_proportion_first_option,
AVG(CASE WHEN operation_status = 200 THEN 1 ELSE 0 END) successful_ops_proportion_second_option,
COUNTIF(operation_status = 200) / COUNT(operation_status) as average_manual
FROM
`requests`
GROUP BY
app_name
这将产生下表(请注意最后 3 列是如何完全相同的,BigQuery 有 2 种 CASE 语法,之后我们有手动比例计算):