2017-09-08 123 views
1

的百分比我有兩個表:我需要計算計數的項目

1:原因

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,我願意聽聽建議

+0

您沒有加入'projects'表。你是不是指「左連接項目」? – Barmar

回答

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更改爲內部聯接。
+0

需要將'count(*)'更改爲'count(projects.id)',否則即使沒有匹配時也會計數1行。 – Barmar