列出百分比

时间:2012-07-02 12:05:51

标签: php mysql join percentage

我正在尝试制作测试答案的百分比。

我有3个表的mysql数据库

tests

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

questions包含测试问题

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我把测试中的所有答案都放在了

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

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

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

1 个答案:

答案 0 :(得分: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示例