Skip to content

Instantly share code, notes, and snippets.

@Niccolum
Last active March 18, 2020 14:11
Show Gist options
  • Save Niccolum/800aedf24b9757a480c08c47abc1c952 to your computer and use it in GitHub Desktop.
Save Niccolum/800aedf24b9757a480c08c47abc1c952 to your computer and use it in GitHub Desktop.
with user_answers as (
select
qa.uuid as questions_answers_id,
CASE
when st.grade::int = 1 then TRUE
else FALSE
END as grade,
CASE
when st.state = 'checked' then TRUE
else FALSE
END as state
from questions_answers qa, jsonb_to_recordset(qa.state) as st(grade float, state text)
), correct_text as (
select
qa.uuid as questions_answers_id,
TRUE as correct_answer
from questions_answers qa
join questions q on q.id = qa.question_id and q.type = 'TX'
), correct_choice as (
select
qa.uuid as questions_answers_id,
CASE
when ua.state = TRUE then TRUE
else FALSE
END as correct_answer
from questions_answers qa
left join user_answers ua on ua.questions_answers_id = qa.uuid and ua.state = TRUE and ua.grade = TRUE
join questions q on q.id = qa.question_id and q.type = 'CH'
), correct_multianswer as (
select
qa.uuid as questions_answers_id,
CASE
when sum(ua.grade::int) = sum(ua.state::int) then TRUE
else FALSE
END as correct_answer
from questions_answers qa
left join user_answers ua on ua.questions_answers_id = qa.uuid and ua.state = TRUE
join questions q on q.id = qa.question_id and q.type = 'MA'
group by qa.id
), correct_answers as (
select questions_answers_id, correct_answer
from correct_text ct
UNION
select questions_answers_id, correct_answer
from correct_choice cc
UNION
select questions_answers_id, correct_answer
from correct_multianswer cm
)
SELECT
ats.id as id,
ats.assessment_id as assessment_id,
ats.status as status,
ats.started_at as start,
ats.completed_at as stop,
array_length(ats.answers, 1) as total_questions,
sum(ca.correct_answer::int) as total_correct_answers
FROM attempts ats
join correct_answers ca on ca.questions_answers_id = ANY(ats.answers)
where ats.completed_at is not NULL
GROUP BY id, assessment_id, status, start, stop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment