Skip to content
Advertisement

get top values in select

I have next ordered table:

types        count
soft         7
lite soft    5
middle soft  4
hard soft    3
other        2

I need to select top values, sum of witch is 15+ (in my case 7+5+4 > 15) and merge items which lefts in to other: result should be:

types        count
soft         7
lite soft    5
middle soft  4
other        5

Advertisement

Answer

You can use a subquery with a cumulative sum:

select (case when running_count - count <= 15 then types else 'other' end) as types,
       sum(count)
from (select t.*, sum(count) over (order by count desc) as running_count
      from t
     ) t
group by (case when running_count - count <= 15 then types else 'other' end)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement