sql - 运行所有先前行 BigQuery 的总计
问题描述
我有一个 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 的所有先前行的总和,其中 category = 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'
我真的很感激这方面的任何帮助!提前致谢
解决方案
category
在where
子句中过滤会驱逐不出现 ' 的(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
推荐阅读
- android - 关于Adapter类如何从HashMap中获取key和value
- http - 强制浏览器使用部分内容下载大文件
- laravel - Laravel Passport createToken 错误
- ios - 在 Appium 上打开 View Controller 非常慢
- algorithm - 如何对所有尺寸的十五个拼图进行最佳洗牌?
- npm - npm install 期间面临的问题
- java - 计算不是每个元素的除数的数组元素的数量
- javascript - SpyOn 一个模拟的笑话模块没有正确地进行间谍活动
- javascript - Hawk auth 适用于 python 请求,但不适用于 JS Axios
- python - Python 从字符串创建一个模块并运行该模块