title: sql setting and using variables in select statements
body: <p>Say for instance you have the following sql:</p>
  
  <pre><code>SELECT 
      attempt.user_id,
      attempt.team_id,
      SUM(CASE
          WHEN attempt.module_type_id IN (3 , 4, 5, 6) THEN attempt.score
      END) / COUNT(CASE
          WHEN attempt.module_type_id IN (3 , 4, 5, 6) THEN 1
      END) as avg_score,
      (SELECT 
              COUNT(atha.academy_module_id)
          FROM
              academy_team_has_academy_module atha
          WHERE
              atha.academy_team_id = attempt.team_id
      ) as num_modules
  
  FROM
      academy_attempt attempt
  GROUP BY attempt.user_id
  </code></pre>
  
  <p>Now you wish to use <code>num_modules</code> to do the following action:</p>
  
  <pre><code>    num_modules / COUNT(attempt.module_id) as completed
  </code></pre>
  
  <p>When i run this i get (as expected) <code>Unknown column num_modules</code></p>
  
  <p>So is there any way i can set it as a variable so i can use the value?</p>