PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

Selecione a contagem de respostas do MCQ com base na resposta da pergunta anterior


Se você não quiser fazer mod, então você precisa selecionar questionID. e eu usei cross join para obter algum outro segmento onde não está em resposta. e na instrução select, você caso instrução para contar segmentName para 0.
SELECT
    bb.name,
    s.name,
    CASE WHEN s.id IN(
        SELECT
            r.segment_id FROM brandlift_respondent r) THEN
        COUNT(q2ac.brand_id)
    ELSE
        0
    END AS CountNumber
FROM
    brandlift b
    LEFT JOIN brandlift_brand bb ON b.campaign_id = bb.campaign_id
    LEFT JOIN brandlift_respondent r ON b.campaign_id = r.campaign_id
    
    CROSS JOIN brandlift_segment s
    
    LEFT JOIN brandlift_question q1 ON b.campaign_id = q1.campaign_id AND q1.ordinal = 1
    LEFT JOIN brandlift_answer q1a ON r.id = q1a.respondent_id AND q1.id = q1a.question_id
    INNER JOIN brandlift_answer_content q1ac ON q1a.id = q1ac.answer_id AND q1ac.brand_id = 1 -- the "flagship brand" id
        
    LEFT JOIN brandlift_question q2 ON q1.campaign_id = q2.campaign_id AND q2.ordinal = 2
    LEFT JOIN brandlift_answer q2a ON q1a.respondent_id = q2a.respondent_id AND q2.id = q2a.question_id
    LEFT JOIN brandlift_answer_content q2ac ON q2a.id = q2ac.answer_id AND bb.id = q2ac.brand_id
WHERE
    b.campaign_id = :campaign_id -- parameter
    AND R.segment_id = s.id OR s.id NOT IN(SELECT r.segment_id FROM brandlift_respondent r)
GROUP BY
    bb.name,
    s.name,
    s.id

o resultado mostra assim