BigQuery:除以列中的值之和以查找比率

时间:2018-04-01 02:59:32

标签: sql google-bigquery legacy-sql

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

我想将其转换为每个bin与所有bin中总计数的比率。

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

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

然后我得到

  

错误:查询失败   错误:SELECT子句

中不允许进行子选择

任何人都可以让我现在正确的方法在BigQuery中做这种简单的划分吗?

2 个答案:

答案 0 :(得分:2)

BigQuery Legacy 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`)

答案 1 :(得分:1)

您正在寻找窗口/分析功能。在标准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