sql - agrregate由多个组计数和共享

时间:2017-09-14 08:57:30

标签: sql postgresql

表格t1如下所示,每个make需要获取每个type

的点数和%份额
+--------+------+
|  make  | type |
+--------+------+
| toyota | car  |
| audi   | suv  |
| bmw    | suv  |
| bmw    | suv  |
| audi   | car  |
+--------+------+

所需的输出如下。

+--------+------+---------------+---------------+
|  make  | type | vehicle_cnt   | vehicle_pct   |
+--------+------+---------------+---------------+
| toyota | car  |             1 |         100.0 |
| audi   | suv  |             1 |         50.0  |
| audi   | car  |             1 |         50.0  |
| bmw    | suv  |             2 |         100.0 |
+--------+------+---------------+---------------+

我可以使用下面的查询通过make(vehicle_cnt)得到每种类型的计数。但是,还需要输入如何获得百分比份额。

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

3 个答案:

答案 0 :(得分:1)

尝试不同的聚合窗口,例如:

select DISTINCT
make
 , type
 , count (*) over (partition by make, type) as vehicle_cnt
 , count (1) over (partition by make, type)*100 / count (1) over (partition by make) as vehicle_pct
 from t1

答案 1 :(得分:0)

使用几个CTE:

with CTE as
(
select
make
 , type
 , count (*) as vehicle_cnt
 from t1
 group by make, type
),
M2 as
(
select type, sum(vehicle_cnt) as tot
from CTE
group by type
)
select CTE.*, 100*(CTE.vehicle_cnt/M2.tot) as pc
from CTE
inner join M2
on m2.type = CTE.type

答案 2 :(得分:0)

select make,
       type,
       count(*) as vehicle_cnt,
       round((count(*) * 100 / (select count(*) from t1)::numeric), 1) as vehicle_pct
  from t1
 group by make, type