title: MySql Sum of Count If
body: <p>I have a table with every login by all users. 
  I want to run a query that will pull the number of times each user logs in but limit it to 4 if the user logged in more than 4 times on a day.
  And then do a sum to get the total number of logins.
  Further to this I want to pull back the time frame for the total number of logins. So I specify the total number of logins as 100 then the query must pull back the earliest date, going back from today and counting the number of logins (limited at 4 if above 4) per user.</p>
  
  <p>My query so far to get the list of totals limited to 4 per user:</p>
  
  <pre><code>SELECT (case when (count(l.user_id) &gt; 4) then 4 else count(l.user_id) end) as cappedcount 
  FROM `logins` l 
  where l.store_id = 908 
  and l.login_dt &gt; '2018-04-17 00:00:00' and l.login_dt &lt; '2018-04-18 23:59:59' 
  group by l.user_id order by cappedcount desc
  </code></pre>
  
  <p>I'm specifying the date range at the moment but don't want to do that in the final query.</p>