sql - Count and take average of not null columns in a single row -


i want count , take average of not null columns in each row example, have table this

name |  | b  | c  | d  | e   | f |      |    |    |    |    |     |   | umar | 2  |null| 3  | 5  | null| 4 | ali  |null|null| 3  |null| 1   | 4 | ali  |null|null| 3  |null| null| 4 | 

the result should

    name |  | b  | c  | d  | e   | f | average          |    |    |    |    |     |   |     umar | 2  |null| 3  | 5  | null| 4 |  3.5     ali  |null|null| 3  |null| 1   | 4 |  2.66     ali  |null|null| 3  |null| null| 4 | 3.5 

var query = x in table             select new              {                 countnotnull = (x.a ?? 0) + (x.b ?? 0) + (x.c ?? 0) + (x.d ?? 0) + (x.e ?? 0) + (x.f ?? 0)              }; 

if don't want count calculate average(you've changed question):

var query =       x in table      let notnullcolcount = (x.a == null ? 0 : 1) + (x.b == null ? 0 : 1) + (x.c == null ? 0 : 1) + (x.d == null ? 0 : 1) + (x.e == null ? 0 : 1) + (x.f == null ? 0 : 1)      let notnullcolsum = (x.a ?? 0) + (x.b ?? 0) + (x.c ?? 0) + (x.d ?? 0) + (x.e ?? 0) + (x.f ?? 0)      select new       {         averagenotnull = notnullcolcount == 0                           ? 0.0                           : 1.0 * notnullcolsum / notnullcolcount       }; 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -