Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a simple table with two columns Bin_name (int) and Count_in_this_bin (int)

I want to convert it to the ratio of each bin to the total count in all bins.

I used the following query in Google BigQuery:

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

Then I get

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

Can anyone let me now the correct way to do this kind of simple divide in BigQuery?

like image 866
Psyduck Avatar asked Nov 25 '25 12:11

Psyduck


1 Answers

BigQuery Legacy SQL

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

BigQuery Standard 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`)
like image 120
Mikhail Berlyant Avatar answered Nov 28 '25 02:11

Mikhail Berlyant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!