BigQuery:除以列中值的总和以找到比率

BigQuery: Divided by sum of values in column to find the ratio

我有一个简单的 table,包含两列 Bin_name (int) 和 Count_in_this_bin (int)

我想把它转换成每个箱子占所有箱子总数的比率。

我在 Google BigQuery 中使用了以下查询:

SELECT count_in_bin/(SELECT SUM(count_in_bin) FROM [table])
FROM [table]

然后我得到

error:Query Failed Error: Subselect not allowed in SELECT clause

谁能告诉我在 BigQuery 中进行这种简单划分的正确方法?

您正在寻找 window/analytic 函数。在标准 SQL 中,这将是:

SELECT count_in_bin / SUM(count_in_bin) OVER () 
FROM [table]

在遗留 SQL 中,您似乎需要一个子查询:

SELECT count_in_bin, count_in_bin / total_count_in_bin
FROM (SELECT count_in_bin, SUM(count_in_bin) OVER () as total_count_in_bin
      FROM [table]
     ) t

旧版 BigQuery SQL

#legacySQL
SELECT 
  count_in_bin, 
  RATIO_TO_REPORT(count_in_bin) OVER() AS ratio
FROM [project:dataset.table]

BigQuery 标准 SQL

#standardSQL
SELECT 
  count_in_bin, 
  count_in_bin / total AS ratio
FROM `project.dataset.table`, 
(SELECT SUM(count_in_bin) total FROM `project.dataset.table`)