2013-07-31 37 views
0

我需要SQL查詢進行分組,其中只包含那些總共包含所有類別的至少80%,其他罕見類別(包含總數的20%)的組的數量,應該表示爲「其他」。前80%類別的分組

所以按類別顏色分組蘋果這樣的查詢的結果應該是這樣的:

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

如何做到這一點?

+0

如果存在多個可能的組,那麼您的查詢將返回什麼?例如。如果你的「其他」含有9%的棕色? –

回答

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小提琴。

+0

感謝Gordon提供了這樣一個及時的答案,是的,它工作正常。也許你知道如何在沒有分析功能的情況下實現相同的功能(對於MySQL)? – sbrbot