很抱歉,我找不到基本答案。
具有2列 car_type 和 event 的简单表格。 每次客户询问汽车时,表中都会记录一条记录,并且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;
但这没用。
提前谢谢!
答案 0 :(得分: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 :(得分: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