2017-09-14 58 views
0

與表t1像下面,需要得到每個make計數以及每個份額做出SQL - 總數量和份額

+--------+ 
| make | 
+--------+ 
| toyota | 
| audi | 
| bmw | 
| bmw | 
| audi | 
+--------+ 

下面我可以得到car_cnt每做

select 
make 
, count (*) as car_cnt 
from t1 
group by make 

我如何獲得每個make的份額(%)?

回答

1

使用COUNT作爲分析功能,我們可以在您的表格上進行一次掃描並計算每輛車的市場份額。

select distinct 
    make, 
    count(*) over (partition by make) as car_cnt, 
    100.0 * count(*) over (partition by make)/count(*) over() as car_pct 
from t1 

輸出:

make car_cnt car_pct 
1 audi 2  40 
2 bmw  2  40 
3 toyota 1  20 

演示在這裏:

Rextester