我需要计算计算物品的百分比

时间:2017-09-08 18:39:56

标签: php mysql sql datatable

我有两张桌子:

第一:原因

id   |   title   
---------------------------------  
1    |   Customer didn't like it  
2    |   Needs improving         
3    |   Wrong format 

第二名:项目

id   |   title       |   rejected
------------------------------------  
1    |   Priject 1   |   Null
2    |   Priject 2   |   1  
3    |   Priject 3   |   1  
4    |   Priject 4   |   Null  
5    |   Priject 5   |   2

出于这个原因,我需要显示Reasons.Title和被拒绝的项目数量。我已经设法将这些表加在一起,使用此代码

SELECT reasons.title as title, count(*) as num
FROM reasons
LEFT JOIN reasons on projects.rejected = reasons.id
WHERE projects.rejectedIS NOT NULL
GROUP BY projects.rejected

现在我需要添加百分比,所以我的最终表格看起来像这样

title                    |   num   |  percentage 
--------------------------------------------------  
Customer didn't like it  |   2     |  66,6
Needs improving          |   1     |  33,3

百分比的格式当然不重要。 我想用MySql完成这个,所以我不需要使用两个查询和额外的PHP,但如果有另一个解决方案,其他来自MySql,我愿意接受建议

1 个答案:

答案 0 :(得分:0)

您可以通过获取FROM子句中的总数来完成此操作:

SELECT r.title as title, count(*) as num,
       COUNT(*) / pp.cnt as ratio
FROM reasons r JOIN 
     projects p
     ON p.rejected = r.id CROSS JOIN
     (SELECT COUNT(*) as cnt FROM projects p WHERE rejects IS NOT NULL) pp
GROUP BY r.title, pp.cnt;

注意:

  • 这会修复表名,因此查询有一个projects表。
  • 这会删除WHERE,因为它不需要。
  • 这会将LEFT JOIN更改为内部联接。