postgresql - sql - aggregate count and share by group -
with table t1
below, need count each make
, share each make
+--------+ | make | +--------+ | toyota | | audi | | bmw | | bmw | | audi | +--------+
with below can get car_cnt per make
select make , count (*) car_cnt t1 group make
how share (%) each make
?
using count
analytic function, can make single pass on table , compute market share each car.
select distinct make, count(*) on (partition make) car_cnt, 100.0 * count(*) on (partition make) / count(*) on () car_pct t1
output:
make car_cnt car_pct 1 audi 2 40 2 bmw 2 40 3 toyota 1 20
demo here:
Comments
Post a Comment