The Problem
Having a web application where users can solve exams consisting of different types of questions (multiple choice, single choice), I need to select the percentage score for a user submission. I am using PostgreSQL 13.x
Schema
exams (id)
questions (id)
answers (id, question_id, correct)
exam_questions (exam_id, question_id)
exam_answers (user_id, exam_id, answer_id)
What I have
I managed to come up with a query, which selects the data I need:
SELECT a.id, a.question_id, a.correct, (CASE WHEN ea.answer_id::bool THEN TRUE ELSE FALSE END) as selected
FROM answers a
FULL OUTER JOIN exam_answers ea
ON a.id = ea.answer_id AND ea.exam_id = ?
WHERE a.question_id IN (
SELECT eq.question_id
FROM exam_questions eq
WHERE eq.exam_id = ?
);
Which returns something like:
|id|question_id|correct|selected|
|--|-----------|-------|--------|
|1 |1 |true |false |
|2 |1 |false |true |
|3 |1 |false |false |
|4 |1 |false |false |
|5 |2 |true |false |
|6 |2 |true |true |
|7 |2 |false |false |
|8 |2 |false |true |
If possible, how can I modify this SQL to find how many questions have their correct answers completely intersect with the selected ones to get the score?
full joinshould not be needed assuming the data has proper foreign key references. (2) desired results would make the question clearer.