我正在学习MySQL,但遇到的问题是我找不到答案。我有一个包含列的数据库:company和company_response。我现在以降序查询这些公司,以便那些已经通过救济方式解决大多数投诉的公司排在第一位。问题是,我现在必须计算“通过救济关闭”实例的比率。还有两个其他的响应选项,我找不到一种方法来创建“比率”列(以救济关闭/所有投诉已关闭),这样我可以在救济金额旁边显示比率。有没有人可以帮助我呢?
实际上,我不知道如何制作“所有实例”和比率列,因为我已经使用了where子句来编写我的Total relieves
列
这是我到目前为止的查询:
SELECT company AS "Company name", count(company_response) AS "Total relieves"
FROM cfpb_complaints_2500
WHERE company_response = "Closed with relief"
GROUP BY company
ORDER BY count(company_response) DESC;
答案 0 :(得分:2)
尝试使用条件计数:
SELECT company AS "Company name",
COUNT(CASE WHEN company_response = 'Closed with relief' THEN 1 END) as "Total Relieves",
COUNT(CASE WHEN company_response = 'Closed with relief' THEN 1 END) / COUNT(*) as "Ratio of Relieves"
FROM cfpb_complaints_2500
GROUP BY company
答案 1 :(得分:1)
您可以使用子查询来计算公司的所有投诉
CREATE tABLE cfpb_complaints_2500 (company int,company_response varchar(100))
insert INTO cfpb_complaints_2500 VALUES (1,"Closed with relief") ,(1,"Closed with relief") ,(1,"Closed without relief") ,(1,"Closed without relief") ,(1,"Closed without relief") ,(1,"Closed without relief"),(2,"Closed with relief") ,(2,"Closed with relief") ,(2,"Closed without relief") ,(2,"Closed without relief")
SELECT company AS "Company name" ,count(company_response) AS "Total relieves" , count(company_response)/ (SELECT count(*) FROM cfpb_complaints_2500 WHERE company = cf.company) AS "ratio" FROM cfpb_complaints_2500 cf WHERE company_response = "Closed with relief" GROUP BY company ORDER BY ratio DESC;
Company name | Total relieves | ratio -----------: | -------------: | -----: 2 | 2 | 0.5000 1 | 2 | 0.3333
db <>提琴here