【发布时间】:2020-07-09 11:30:49
【问题描述】:
我需要计算运行总计,但需要在某个条件下重置总计(当预期达到 = 0 并且 product_group 和产品更改时)。在没有两个额外字段的情况下在这里获得帮助:Calculate a running total with a condition in BigQuery 我有这张表,可以使用 product_group 和 product 作为整数或字符串,如下所示。
Date, Product_group, Product, Registrations, Expected Registrations, Expected Reached, Running Total
2020-03-01,A, Bikes, 5, 4,1, 1
2020-03-02,A, Bikes, 7, 5,1, 2
2020-03-03,A, Bikes, 8, 6,1, 3
2020-03-04,A, Bikes, 2, 5,0, 0
2020-03-05,A, Bikes, 5, 4,1, 1
2020-03-06,A, Bikes, 7, 5,1, 2
2020-03-04,B, Cars , 2, 5,0, 0
2020-03-05,B, Cars , 5, 4,1, 1
2020-03-06,B, Cars , 7, 5,1, 2
2020-03-07,B, Cars , 8, 6,1, 3
2020-03-08,C, Plane, 2, 5,0, 0
有关如何调整此查询(来自另一篇帖子的答案)的任何建议,在没有两个额外字段的情况下可以正常工作-
#standardSQL
SELECT * EXCEPT(grp),
SUM(Expected_reached) OVER(PARTITION BY grp ORDER BY `date`) Running_Total
FROM (
SELECT *, COUNTIF(Expected_reached = 0) OVER(ORDER BY `date`) grp
FROM `project.dataset.table`
)
问题是 COUNTIF(Expected_reached = 0) OVER(ORDER BYdate) grp 在 product_group 或 product 更改并且我得到非唯一组时重新开始,因此运行总数 SUM(Expected_reached) OVER(PARTITION BY grp ORDER BYdate) Running_Total 计算不正确。
【问题讨论】:
标签: sql google-cloud-platform google-bigquery window-functions gaps-and-islands