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

问题描述 投票:0回答:2

对基本问题的道歉,搜索后我找不到答案。

具有2列car_typeevent的简单表。每次客户询问汽车时,都会在表中放入一条记录,并且event =“ inquire”。如果购买了该类型的汽车,则会放入事件=“购买”的记录。

根据#购买/#查询,我将如何计算哪种车型最成功?按课程类型分组。

我已经尝试过

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;

但是这没有用。

谢谢你!

mysql sql percentage
2个回答
1
投票

您可以使用条件聚合:

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;

1
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.