title: Aggregate the long tail of a group by query into "others"
body: <p>I have a table with one dimension and one metric:</p>
  
  <pre><code>name metric
  A   4
  A   9
  B   27
  C   9
  D   6
  </code></pre>
  
  <p>I want to group by the dimension and then group the long tail of the results into an 'others' or 'the rest of the data' label.</p>
  
  <p>For example my query should return all the names that the sum of their metrics are greater than 10 and group the rest into 'others':</p>
  
  <pre><code>name    metric
  A       13
  others  15
  B       27
  </code></pre>
  
  <p>I can get this result by aggregating twice:</p>
  
  <pre class="lang-sql prettyprint-override"><code>with T as ( 
    select 
      name
    , (case when sum(metric) &gt; 10 then name else 'others' end) as group_name
    , sum(metric) as metric
    from MyData
    group by name
  )
  
  select 
    group_name as name
  , sum(metric) as metric 
  from T 
  group by group_name
  order by metric
  </code></pre>
  
  <p>Can I do this in a single operation without using sub queries?</p>
  
  <p><a href="https://rextester.com/DFWP54026" rel="nofollow noreferrer">SQL Snippet</a></p>