我有一个 BigQuery 表,如下所示:
ID SessionNumber CountOfAction Category
1 1 1 B
1 2 3 A
1 3 1 A
1 4 4 B
1 5 5 B
我正在尝试获取 CountofAction 的所有先前行的运行总计,其中类别 = A。最终输出应该是
ID SessionNumber CountOfAction
1 1 0 --no previous rows have countofAction for category = A
1 2 0 --no previous rows have countofAction for category = A
1 3 3 --previous row (Row 2) has countofAction = 3 for category = A
1 4 4 --previous rows (Row 2 and 3) have countofAction = 3 and 1 for category = A
1 5 4 --previous rows (Row 2 and 3) have countofAction = 3 and 1 for category = A
下面是我编写的查询,但它没有给出我想要的输出
select
ID,
SessionNumber ,
SUM(CountofAction) OVER(Partition by clieIDntid ORDER BY SessionNumber ROWS BETWEEN UNBOUNDED
PRECEDING AND 1 PRECEDING)as CumulativeCountofAction
From TAble1 where category = 'A'
我真的很感激任何帮助!提前致谢
最佳答案
在 where
子句中对 category
进行过滤会逐出 (id, sessionNumber)
元组,其中 category
'A
' 没有出现,这不是您想要的。
相反,您可以使用聚合和条件 sum()
:
select
id,
sessionNumber,
sum(sum(if(category = 'A', countOfAction, 0))) over(
partition by id
order by sessionNumber
rows between unbounded preceding and 1 preceding
) CumulativeCountofAction
from mytable t
group by id, sessionNumber
order by id, sessionNumber
关于sql - BigQuery 所有先前行的运行总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61602997/