前80%类别的分组

时间:2013-07-31 13:23:23

标签: sql group-by

我需要SQL查询按某些类别进行分组,这些类别只会显示总数中包含至少80%所有类别的数量,其他稀有类别(最多占总数的20%)应表示为“其他” ”

因此,按类别颜色对苹果进行分组的查询结果应如下所示:

RED    1118 44% )
YELLOW  711 28% > at least 80%
GREEN   229  9% )
other   482 19%

怎么做?

1 个答案:

答案 0 :(得分:0)

我会通过聚合和分析功能的组合来实现这一点。当最稀有的累积总和低于20%时,颜色将被置于“其他”类别中:

select (case when cumcntdesc < totalcnt * 0.2 then 'other'
             else color
        end) as color, sum(cnt) as cnt
from (select color, count(*) as cnt,
             sum(count(*)) over (order by count(*) asc) as cumcntdesc,
             sum(count(*)) over () as totalcnt
      from t
      group by color
     ) t
group by (case when cumcntdesc < totalcnt * 0.2 then 'other'
               else color
          end)

Here是一个SQL小提琴。