Как мне упростить запрос?
Ниже приведен один из вариантов, я думаю
#standardSQL
CREATE TEMP FUNCTION f(code INT64, bits INT64) AS (
IF(code >> bits = 1, 1, 0)
);
SELECT (CASE
WHEN (SUM(f(status_code, 4)) +
SUM(f(status_code, 3))) / COUNT(*) > 0.75 THEN 0
WHEN (SUM(f(status_code, 4)) +
SUM(f(status_code, 3)) +
SUM(f(status_code, 2))) / COUNT(*) > 0.75 THEN 1
WHEN (SUM(f(status_code, 4)) +
SUM(f(status_code, 3)) +
SUM(f(status_code, 2)) +
SUM(f(status_code, 1))) / COUNT(*) > 0.75 THEN 2
ELSE 3
END) AS status
FROM `project.dataset.table`
или дальнейшее «рефакторинг» дает:
#standardSQL
CREATE TEMP FUNCTION f(code INT64, bits INT64) AS (
IF(code >> bits = 1, 1, 0)
);
SELECT
(CASE
WHEN SUM(f(status_code, 4) + f(status_code, 3)) / COUNT(*) > 0.75 THEN 0
WHEN SUM(f(status_code, 4) + f(status_code, 3) + f(status_code, 2)) / COUNT(*) > 0.75 THEN 1
WHEN SUM(f(status_code, 4) + f(status_code, 3) + f(status_code, 2) + f(status_code, 1)) / COUNT(*) > 0.75 THEN 2
ELSE 3
END) AS status
FROM `project.dataset.table`
и возможно сделает его более производительным ...
Итак, наконец
#standardSQL
CREATE TEMP FUNCTION f(code INT64, bits INT64) AS (
IF(code >> bits = 1, 1, 0)
);
SELECT
(CASE
WHEN f4 + f3 > 0.75 THEN 0
WHEN f4 + f3 + f2 > 0.75 THEN 1
WHEN f4 + f3 + f2 + f1 > 0.75 THEN 2
ELSE 3
END) AS status
FROM (
SELECT
SUM(f(status_code, 4))/ COUNT(*) f4,
SUM(f(status_code, 3))/ COUNT(*) f3,
SUM(f(status_code, 2))/ COUNT(*) f2,
SUM(f(status_code, 1))/ COUNT(*) f1
FROM `project.dataset.table`
)