0

私はテストの答えのパーセンテージを作ろうとしています。

私は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
4

1 に答える 1

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の例を参照してください

于 2012-07-02T12:09:04.267 に答える