add question stat query

This commit is contained in:
Pavel 2024-03-17 17:41:24 +03:00
parent 32b57399b0
commit ca9f6ee46c

@ -478,3 +478,86 @@ FROM
ResultStats rs ON tb.time_interval = rs.time_interval
LEFT JOIN
AvTimeStats at ON tb.time_interval = at.time_interval;
-- name: QuestionsStatistics :many
WITH Funnel AS (
SELECT
COUNT(DISTINCT session) FILTER (WHERE a.start = FALSE) AS count_start_false,
COUNT(DISTINCT session) FILTER (WHERE a.start = TRUE) AS count_start_true,
COUNT(DISTINCT CASE WHEN a.result = FALSE AND qid_true_result IS NOT NULL THEN session END) AS count_f_result_with_t_question,
COUNT(DISTINCT CASE WHEN a.start = TRUE AND qid_true_result IS NULL THEN session END) AS count_t_start_with_t_question,
COUNT(DISTINCT session) FILTER (WHERE a.result = TRUE) AS count_t_result
FROM
answer a
LEFT JOIN (
SELECT DISTINCT a.session, q.id AS qid_true_result
FROM answer a
JOIN question q ON a.question_id = q.id
WHERE a.result = TRUE
) AS q ON a.session = q.session
WHERE
a.quiz_id = $1
AND a.created_at >= TO_TIMESTAMP($2)
AND a.created_at <= TO_TIMESTAMP($3)
),
Results AS (
SELECT
q.title AS question_title,
COUNT(*)::FLOAT / NULLIF(SUM(COUNT(*)) FILTER (WHERE a.result = TRUE), 0) AS percentage
FROM
answer a
JOIN
question q ON a.question_id = q.id
WHERE
a.quiz_id = $1
AND a.created_at >= TO_TIMESTAMP($2)
AND a.created_at <= TO_TIMESTAMP($3)
AND a.result = TRUE
GROUP BY
q.id, q.title
HAVING
COUNT(*) >= 1
),
Questions AS (
SELECT
q.title AS question_title,
a.content AS answer_content,
COUNT(*)::FLOAT / NULLIF(q.total_answers, 0) AS percentage
FROM
answer a
JOIN (
SELECT q.id, COUNT(*) AS total_answers
FROM question q
JOIN answer a ON q.id = a.question_id
WHERE a.quiz_id = $1
AND a.created_at >= TO_TIMESTAMP($2)
AND a.created_at <= TO_TIMESTAMP($3)
GROUP BY q.id
) q ON a.question_id = q.id
WHERE
a.quiz_id = $1
AND a.created_at >= TO_TIMESTAMP($2)
AND a.created_at <= TO_TIMESTAMP($3)
GROUP BY
q.id, q.title, a.content
HAVING
COUNT(*) >= 1
)
SELECT
Funnel.count_start_false,
Funnel.count_start_true,
Funnel.count_f_result_with_t_question,
Funnel.count_t_start_with_t_question,
Funnel.count_t_result,
Funnel.count_start_true,
Results.question_title AS results_question_title,
Results.percentage AS results_percentage,
Questions.question_title AS questions_question_title,
Questions.answer_content AS questions_answer_content,
Questions.percentage AS questions_percentage
FROM
Funnel,
Results,
Questions;