title: Calculating multiple column average in SQLite3
body: <p>I need to average some values in a <em>row</em>-wise fashion, rather than a <em>column</em>-wise fashion.  (If I were doing a column-wise average, I could just use <code>avg()</code>).  My specific application of this requires me ignore NULLs in averaging.  It's pretty straightforward logic, but seems awfully difficult to do in SQL.  Is there an elegant way of doing my calculation?</p>
  
  <p>I'm using SQLite3, for what it's worth.</p>
  
  <p><strong>Details</strong></p>
  
  <p>If you need more details, here's an illustration:</p>
  
  <p>I have a a table with a survey:</p>
  
  <pre><code>| q1 | q2    | q3    | ... | q144 |
  |----|-------|-------|-----|------|
  | 1  | 3     | 7     | ... | 2    |
  | 4  | 2     | NULL  | ... | 1    |
  | 5  | NULL  | 2     | ... | 3    |
  </code></pre>
  
  <p>(Those are just some example values and simple column names.  The valid values are 1 through 7 and NULL.)</p>
  
  <p>I need to calculate some averages like so:</p>
  
  <pre><code>q7 + q33 + q38 + q40 + ... + q119 / 11 as domain_score_1
  q10 + q11 + q34 + q35 + ... + q140 / 13 as domain_score_2
  ...
  q2 + q5 + q13 + q25 + ... + q122 / 12 as domain_score_14
  </code></pre>
  
  <p>...but i need to pull out the nulls and average based on the non-nulls.  So, for <code>domain_score_1</code> (which has 11 items), I would need to do:</p>
  
  <pre><code>Input:  3, 5, NULL, 7, 2, NULL, 3, 1, 5, NULL, 1
  
  (3 + 5 + 7 + 2 + 3 + 1 + 5 + 1) / (11 - 3)
  27 / 8
  3.375
  </code></pre>
  
  <p>A simple algorithm I'm considering is:</p>
  
  <p>Input:</p>
  
  <pre><code>3, 5, NULL, 7, 2, NULL, 3, 1, 5, NULL, 1 
  </code></pre>
  
  <p>Coalesce each value to 0 if NULL:</p>
  
  <pre><code>3, 5, 0, 7, 2, 0, 3, 1, 5, 0, 1
  </code></pre>
  
  <p>Sum:</p>
  
  <pre><code>27
  </code></pre>
  
  <p>Get the number of non-zeros by converting values > 0 to 1 and sum:</p>
  
  <pre><code>3, 5, 0, 7, 2, 0, 3, 1, 5, 0, 1
  1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1
  8
  </code></pre>
  
  <p>Divide those two numbers</p>
  
  <pre><code>27 / 8
  3.375
  </code></pre>
  
  <p>But that seems like a lot more programming than this should take.  Is there an elegant way of doing this that I'm not aware of?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>Unless I'm misunderstanding something, <code>avg()</code> won't work for this.  Example of what I would want to do:</p>
  
  <pre><code>select avg(q7, q33, q38, ..., q119) from survey;
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>SQL error near line 3: wrong number of arguments to function avg()
  </code></pre>