Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bigquery - Average between columns ignoring NULL values

TL;DR: Is there an easy way to calculate the average between a group of columns on google's bigquery?

I have a table with many estimates from a continuous variable, I'm giving an example with only three columns but the original table have something between 8 columns:

Estimate_A Estimate_B Estimate_C
4 2 3
1 2 2
4 NULL 2
2 3 NULL
4 NULL NULL

I want to produce a new column AVG_ESTIMATE which is an AVERAGE between these estimate columns but ignoring the NULL data

Estimate_A Estimate_B Estimate_C AVG_ESTIMATE
4 2 3 3
1 2 2 1.66
4 NULL 2 3
2 3 NULL 2.5
4 NULL NULL 4
like image 897
jmauricio Avatar asked May 08 '26 16:05

jmauricio


1 Answers

Consider below solution

select *, 
  (select round(avg(Estimate), 2) 
  from unnest([Estimate_A, Estimate_B, Estimate_C]) Estimate
  ) as AVG_ESTIMATE
from `project.dataset.table`    

If applied to sample data in your question - output is

enter image description here

like image 96
Mikhail Berlyant Avatar answered May 10 '26 09:05

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!