MySQL average of non-null columns -


i've kludged way through doing this, feel there's cleaner/faster/better solution, , keen learn:

update mytable set favg =  (coalesce(f1,0) + coalesce(f2,0) + coalesce(f3,0) + coalesce(f4,0))  /  ( case when f1 not null 1 else 0 end +  case when f2 not null 1 else 0 end +  case when f3 not null 1 else 0 end + case when f4 not null 1 else 0 end  ) 

so, how can improved?

you can simplify count taking advantage of fact mysql treats booleans integers in numeric context:

update mytable     set favg = (coalesce(f1,0) + coalesce(f2,0) + coalesce(f3,0) + coalesce(f4,0)) /                ((f1 not null) + (f2 not null) + (f3 not null) + (f4 not null)); 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -