简体   繁体   中英

Calculate average of some columns, not counting null values

I have a table with some readings that looks like this:

id  foo   bar   baz   qux
1   2     4     NULL  3            
2   6     11    0     2

I want to calculate an average of some columns, not including null values in the count. Something like this pseudo-code:

select (foo+bar+baz)/countNonNulls(foo,bar,baz) AS result 
  FROM readings WHERE id=1;

Ie, my expected result is (2+4)/2 = 3.

Is there a way to do this in a single SQL query?

In MySQL, you can use:

select (coalesce(foo, 0) + coalesce(bar, 0) + coalesce(baz, 0) /
        ((foo is not null) + (bar is not null) + (baz is not null))
       ) as average

Note that this assumes that at least one value is not null, to prevent division by 0.

To handle the general case, you can use case:

select (case when coalesce(foo, bar, bz) is not null
             then (coalesce(foo, 0) + coalesce(bar, 0) + coalesce(baz, 0) /
                   ((foo is not null) + (bar is not null) + (baz is not null))
                  )
        end) as average

尝试where子句:其中[nameColumn]不为null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM