title: MySQL CASE statement with subquery for histogram
body: <p>I'm attempting to gather data to create a histogram. I want to create histogram of number of times users login to the system. My goal is to utilize the function from <a href="https://stackoverflow.com/a/14860992">this</a> answer, but if there is a better way, that's fine with me too.</p>
  
  <p>My login table is similar to this:</p>
  
  <pre><code>datetime | userid
  </code></pre>
  
  <p>My first step is to get a count of the number of times a user has logged in:</p>
  
  <pre><code>select count(userid) from logins group by userid
  </code></pre>
  
  <p>This returns a nice result set that is similar to:</p>
  
  <pre><code>1325
  761
  4012
  1204
  662
  1841
  15
  1698
  ...
  </code></pre>
  
  <p>My question is, how can I adapt this to utilize the <code>SELECT CASE WHEN</code> method from the linked answer. That code looks like this:</p>
  
  <pre><code>SELECT CASE WHEN age BETWEEN 13 AND 17 THEN '13-17' 
              WHEN age BETWEEN 18 AND 25 THEN '18-25' 
              ELSE '26+' END AS AgeGroup,
      COUNT(*) AS total
  FROM MyTable
  GROUP BY AgeGroup
  </code></pre>
  
  <p>In my case, though, <code>age</code> in the <code>WHEN</code> clauses, is a subquery that I don't think needs to be run for each <code>WHEN</code>. What is an efficient way to utilize the counts I have to use in these bins?</p>