sql - BigQuery 所有先前行的运行总计

标签 sql group-by google-bigquery sum window-functions

我有一个 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/

相关文章:

sql - 选择 a 和下一个是 c 的位置,跳过 b

Mysql - 转换非空值第 2 部分

MySQL 添加到具有分组依据的列不显示所有行

Python/Django 过滤组中具有最大值的行

performance - 分析云数据流 BigQuery 吞吐量/流水线

google-bigquery - 如何在 BigQuery 中执行 Pandas 列转换?

google-analytics - bigquery 中的 GA4 流量源数据不正确

mysql - WHERE 子句后跟 OR 然后再 WHERE

mysql - 将 IN 与子查询一起使用

pandas - pandas groupby 中的自定义聚合函数