根据一列中的值按组计算百分比

Calculate percentage by group based on values in one column

很抱歉,基本问题,我搜索后找不到答案。

一个简单的 table,包含 2 列 car_type 事件 。 每次客户查询汽车时,都会将记录放入 table 和 event = "inquire"。如果购买了该车型,则记录事件 = "bought"。

我如何根据 # 购买 / # 查询来计算哪种车型最成功?当然是按车型分组。

我试过了

select car_type, 
      ((select count(*) from TABLE where event = "bought" ) / 
       (select count(*) from alerts where event = "inquire") * 100.0) as percentage
from TABLE 
group by car_type;

但这没有用。

提前致谢!

您可以使用条件聚合:

select car,
       (sum( event = 'bought') /
        sum( event = 'inquire' )
       ) as bought_inquire_ratio
from t
group by car;

如果您只是想要购买的整体比例,您可以使用:

select car,
       avg( event = 'bought' )
from t
group by car;

您可以对每辆汽车的不同事件类型求和(在子查询中最容易),然后除以结果以获得百分比,按该值降序排序并仅取最高值:

SELECT car_type, 100.0 * bought / inquiries AS percentage
FROM (
    SELECT car_type,
           SUM(event = 'bought') AS bought,
           SUM(event = 'inquire') AS inquiries
    FROM alerts
    GROUP BY car_type
) c
ORDER BY percentage DESC
LIMIT 1