PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Seleziona il conteggio delle risposte MCQ in base alla risposta della domanda precedente

Se non vuoi fare mod, devi invece selezionare questionID. E io ho usato cross join per ottenere qualche altro segmento in cui non risponde. e nella dichiarazione select, tu caso istruzione per contare segmentName a 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

il risultato si vede così