2012-07-02 161 views
0

我正在尝试做出测试答案的百分比。带百分比的列表

我有MySQL数据库与测试问题

id | name  | test_id 
---+------------+-------- 
1 | question 1 | 1 
2 | question 2 | 1 
3 | question 3 | 1 
4 | question 4 | 1 
5 | question 1 | 2 
6 | question 2 | 2 
7 | question 3 | 2 
8 | question 4 | 2 

answers,我把所有的答案,从测试3个表

tests

id | name 
---+-------- 
1 | test 1 
2 | test 2 

questions

id | question_id 
---+------------- 
1 | 1 
2 | 2 
3 | 5 
4 | 6 
5 | 7 
6 | 8 

如何在测试中获得已完成问题百分比的列表。在这种情况下是这样的:

name | percentage 
-------+----------- 
test 1 | 50 
test 2 | 100 
+0

你在哪里得到的百分比是多少? – jcho360

+0

我应该计算它们 - 100 *计数(来自特定测试的答案)/计数(来自特定测试的所有答案) – Goldie

回答

3

尝试

select t.name, 
     cast((count(a.id)/count(q.id)) * 100 as unsigned) as percentage 
from tests t 
left outer join questions q on q.test_id = t.id 
left outer join answers a on a.question_id = q.id 
group by t.name 

请参见本SQLFiddle例如

+0

它不起作用。 – Goldie

+0

我更新了我的答案,结果我得到了100。 –

+0

而且你更新得很好。谢谢。 – Goldie