如何在 Google-Bigquery 中添加基于条件和条件重置的自动增量计数器
How do I add an autoincrement Counter based on Conditions and conditional reset in Google-Bigquery
我的 table 在大查询中,但在根据条件获取增量字段时遇到问题。
基本上每次分数低于 95% 时,第一周都是 returns 第一阶段。如果它连续第二周低于 95%,则 returns 第 2 阶段等等,但是,如果它超过 95%,计数器将重置为“良好”。然后 returns 阶段 1 如果低于 95% 等等
您可以使用 row_number()
-- 但在根据每行 > 95% 的值的计数分配一个组之后:
select t.*,
(case when row_number() over (partition by grp order by month, week) = 1
then 'Good'
else concat('Stage ', row_number() over (partition by grp order by month, week) - 1)
end) as level
from (select t.*,
countif(score > 0.95) over (order by month, week) as grp
from t
) t;
考虑以下
select * except(grp),
(case when Average_score >= 95 and 1 = row_number() over grps then 'Good'
else format('Stage %i', row_number() over grps - sign(grp))
end) as Level
from (
select *, countif(Average_score >= 95) over (order by Month, Week) as grp
from `project.dataset.table`
)
window grps as (partition by grp order by Month, Week)
如果应用于您问题中的示例数据 - 输出为
我的 table 在大查询中,但在根据条件获取增量字段时遇到问题。
基本上每次分数低于 95% 时,第一周都是 returns 第一阶段。如果它连续第二周低于 95%,则 returns 第 2 阶段等等,但是,如果它超过 95%,计数器将重置为“良好”。然后 returns 阶段 1 如果低于 95% 等等
您可以使用 row_number()
-- 但在根据每行 > 95% 的值的计数分配一个组之后:
select t.*,
(case when row_number() over (partition by grp order by month, week) = 1
then 'Good'
else concat('Stage ', row_number() over (partition by grp order by month, week) - 1)
end) as level
from (select t.*,
countif(score > 0.95) over (order by month, week) as grp
from t
) t;
考虑以下
select * except(grp),
(case when Average_score >= 95 and 1 = row_number() over grps then 'Good'
else format('Stage %i', row_number() over grps - sign(grp))
end) as Level
from (
select *, countif(Average_score >= 95) over (order by Month, Week) as grp
from `project.dataset.table`
)
window grps as (partition by grp order by Month, Week)
如果应用于您问题中的示例数据 - 输出为