title: DATEDIFF if a value IS NOT NULL
body: <p>This is a follow-up of this <a href="https://stackoverflow.com/questions/34525443/datediff-replace-null-with-now">question</a> which i posted earlier.</p>
  
  <p>I am calculating the SUM of DATEDIFF using following syntax</p>
  
  <pre><code>SUM(DATEDIFF(COALESCE(e.time_period_to, NOW()), e.time_period_from)) / COUNT(DISTINCT e.company_id)
  </code></pre>
  
  <p>What i want now is to calculate <code>SUM</code> of <code>DATEDIFF</code> only if <code>e.time_period_from is NOT NULL</code></p>
  
  <p>I tried following query.</p>
  
  <pre><code>SUM(IF(e.time_period_from IS NOT NULL), DATEDIFF(COALESCE(e.time_period_to, NOW()), e.time_period_from), 0) / COUNT(DISTINCT e.company_id)
  </code></pre>
  
  <p>This gives me SQL syntax error.</p>
  
  <p>How to go about it ?</p>
  
  <p>UPDATE : </p>
  
  <p>Here is my full MySQL Query</p>
  
  <pre><code>SELECT
      SQL_CALC_FOUND_ROWS
      u.id,
      u.name,
      u.email,
      COUNT(DISTINCT(question_id)) as number_of_answered_questions,
      (SELECT option_id FROM answer WHERE user_id = u.id GROUP BY option_id ORDER BY COUNT(option_id) DESC LIMIT 1) as option_id,
      SUM(IF(e.time_period_from IS NOT NULL), DATEDIFF(COALESCE(e.time_period_to, NOW()), e.time_period_from), 0) / COUNT(DISTINCT e.company_id) AS tenure_in_days
  FROM
      user u
  LEFT JOIN
      role r ON (r.id = u.role_id)
  LEFT JOIN
      answer a ON (a.user_id = u.id)
  LEFT JOIN
      employment e ON (e.user_id = u.id)
  WHERE
      r.slug = 'app_user'
  GROUP BY
      u.id
  LIMIT
      0, 10
  </code></pre>
  
  <p>As you see this is for a sub select i cannot put a where condition outside of it.</p>
  
  <p>And here is the error i get.</p>
  
  <pre><code>"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '), DATEDIFF(COALESCE(e.time_period_to, NOW()), e.time_period_from), 0) / COUNT(D' at line 1"
  </code></pre>
  
  <p>Thanks.</p>