在BigQuery中计算并运行总数/总和

时间:2018-02-16 20:13:52

标签: sql google-bigquery running-total

我在Google Cloud BigQuery中有一个包含两列的表:第一列是日期,第二列是布尔值。我按照日期排序。现在我只想添加两列: 1.简单地计算每行之前的行数:1,2,3,... 2.计算每行之前具有TRUE值的行数(运行总和为True)。 我如何在SQL中执行此操作? 以下显示了解释我的意思的所有列:

enter image description here

1 个答案:

答案 0 :(得分:4)

以下是BigQuery Standard SQL

#standardSQL
WITH `project.dataset.table` AS (
  SELECT '2018-01-01' dt, TRUE value UNION ALL
  SELECT '2018-01-07', FALSE UNION ALL
  SELECT '2018-01-09', TRUE UNION ALL
  SELECT '2018-02-02', TRUE UNION ALL
  SELECT '2018-02-19', FALSE UNION ALL
  SELECT '2018-03-02', FALSE UNION ALL
  SELECT '2018-03-09', FALSE UNION ALL
  SELECT '2018-04-28', TRUE
)
SELECT *,
  COUNT(1) OVER(ORDER BY dt) count_previous_all,
  COUNTIF(value) OVER(ORDER BY dt) count_previous_true
FROM `project.dataset.table`
ORDER BY dt   

结果为

Row dt          value   count_previous_all  count_previous_true  
1   2018-01-01  true    1                   1    
2   2018-01-07  false   2                   1    
3   2018-01-09  true    3                   2    
4   2018-02-02  true    4                   3    
5   2018-02-19  false   5                   3    
6   2018-03-02  false   6                   3    
7   2018-03-09  false   7                   3    
8   2018-04-28  true    8                   4