sql - 聚合计数和按组分享

时间:2017-09-14 06:02:29

标签: postgresql

如下表t1所示,需要按每个make计算每个品牌的份额

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

以下我可以获得car_cnt per make

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

如何获取每个make的份额(%)?

1 个答案:

答案 0 :(得分: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