在下图中,“输出”列是我想在sql中实现的结果。 “LOGIC”列定义何时执行递归加法以及何时将计数器重置为 1。递归加法只是 D 的当前值 + E 的先前值。如果 C 列为 TRUE,则将此计数器重置为 1。
我尝试过递归 CTE 和窗口函数调用,它们可以很好地获取计数器值(D3+E2),但在将计数器重置为 1 时却无法做到这一点。它只是继续获取计数器。在图像中,我已经标记了失败的行。
WITH RunningTotal AS (
SELECT
id,
logic,
val,
SUM(CASE WHEN logic = TRUE THEN 1 ELSE val END) OVER (ORDER BY id) AS output
FROM
`my_table`
)
SELECT
id,
logic,
val,
output
FROM
RunningTotal;
您需要使用两个窗口函数。
logic
列分隔 id 的计数部分。每次 logic
字段为 true 时,新列 logic_run
中的值就会增加 1。sum_over
是每个 logic_run
分区的总和。由于您希望在 val
为 true 时将 logic
设置为 1,因此需要在总和中添加 if
语句,如 output
列所示。WITH example_data AS (SELECT *,id in (2,6) as logic, mod(id-1,5) as val
FROM UNNEST(GENERATE_ARRAY(2,8)) AS id),
table1 as (
SELECT *, countif(logic) over win1 as logic_run
FROM example_data
window win1 as (order by id rows between unbounded preceding and current row)
)
SELECT *,
sum(val) over win2 as sum_over,
sum(if(logic,1,val)) over win2 as output
from table1
window win2 as (partition by logic_run order by id rows between unbounded preceding and current row)