title: WHERE clause inside COUNT(DISTINCT) clause
body: <p>this is a question asked by Ryan Frank on forums.mysql.com, which i am facing as well.</p>
  
  <p>I have the following in the beginning of my SELECT statement:</p>
  
  <pre><code>SELECT accounts.id, accounts.company, accounts.first, accounts.last,
  COUNT(DISTINCT accounts_log.login_time) AS visits,
  COUNT(DISTINCT accounts_log.ip_address) AS visitors,
  COUNT(DISTINCT documents_log.access_time) AS docs,
  MAX(accounts_log.login_time) AS login_time
  FROM accounts
  </code></pre>
  
  <p>This returns all of the variables I need; however, I want to limit the variables that use COUNT(DISTINCT) to a date range. I can’t use the WHERE clause after the FROM clause. For example:</p>
  
  <pre><code>FROM accounts
  WHERE accounts_log.login_time &gt;='$search_from' AND accounts_log.login_time &lt;='$search_to'
  </code></pre>
  
  <p>wouldn’t work because it wouldn’t give me ALL accounts like I need.</p>
  
  <p>I’m looking for something like:</p>
  
  <pre><code>COUNT(DISTINCT accounts_log.login_time WHERE accounts_log.login_time &gt;='$search_from' AND accounts_log.login_time &lt;='$search_to') AS visits
  </code></pre>
  
  <p>P.S. I know the above doesn’t work and have run out of syntax options.</p>