title: Finding top 3 IDs with the largest count, by group - is it possible to avoid a triple nested query?
body: <p>I need to find the top 3 'UserIDs' by 'Time' in terms of count in the 'Table'. An example of the input and output:</p>
  
  <p>Table</p>
  
  <pre><code>ID    UserID    Time
  1       A        '1'
  2       A        '1'
  3       B        '2'
  4       B        '4'
  5       B        '4'
  etc
  </code></pre>
  
  <p>Desired result:</p>
  
  <pre><code>Time    UserID    Number    Rank
   '1'      A         17       1
   '1'      C         11       2
   '1'      Q         9        3
   '2'      B         13       1
   '2'      C         9        2
   '2'      M         7        3
  etc
  </code></pre>
  
  <p>I've been able to accomplish this using a triple query but is there any way to simplify?</p>
  
  <pre><code>select userID, Number, time, Rank from (
  
  select userID, Number, time,
  Rank() over (partition by time order by Number DESC) as Rank
  
  from
  
  (select count(distinct(ID)) as Number, 
  userID, 
  time from table
  group by 2, 3)
  
  )
  
  where Rank &lt;= 3
  </code></pre>
  
  <p>I'm wondering if something like a 'HAVING' clause would be applicable here, since it seems like this would be very slow otherwise.</p>