将计数添加到复杂的SQL查询中

时间:2012-04-10 13:45:20

标签: sql sql-server-2005

我有以下查询返回测试问题,这些问题的可能答案以及用户选择每个可能答案的次数:

SELECT  p.program_id, 
        p.pre_survey_form_id, 
        p.post_survey_form_id, 
        fq.form_id, 
        sq.question_id, 
        sq.question_text, 
        qo.question_option_id, 
        qo.option_text, 
        G.Total

FROM    dbo.program p
        LEFT OUTER JOIN dbo.form_question fq
            ON p.pre_survey_form_id = fq.form_id OR p.post_survey_form_id = fq.form_id
        LEFT OUTER JOIN dbo.survey_question sq
            ON fq.question_id = sq.question_id
        LEFT OUTER JOIN dbo.question_option qo 
            ON sq.question_id = qo.question_id
        LEFT OUTER JOIN (
            SELECT ra.question_id, ra.question_option_id, COUNT(*) AS Total
            FROM dbo.form_response_answers ra
            GROUP BY ra.question_option_id, ra.question_id 
        ) G
            ON G.question_id = sq.question_id AND G.question_option_id = qo.question_option_id

ORDER BY p.program_id, fq.form_id, sq.question_id, qo.question_option_id

我唯一需要的是总结每个问题的回复数量,但我真的磕磕绊绊。我将计算响应数量并获得用户选择特定响应的百分比。

结果集:

----  ----  ----  --  ---------------------------------------------------------------------------  -  ------------  ----
1000  1001  1000  10  How many days a week do you drink at least eight glasses (64 oz.) of water?  1  Never         1
1000  1001  1000  10  How many days a week do you drink at least eight glasses (64 oz.) of water?  2  Once          1
1000  1001  1000  10  How many days a week do you drink at least eight glasses (64 oz.) of water?  3  Two times     NULL
1000  1001  1000  10  How many days a week do you drink at least eight glasses (64 oz.) of water?  4  Three times   2
1000  1001  1000  10  How many days a week do you drink at least eight glasses (64 oz.) of water?  5  Four times    NULL
1000  1001  1000  10  How many days a week do you drink at least eight glasses (64 oz.) of water?  6  Five or more  NULL

1 个答案:

答案 0 :(得分:5)

如果我正确理解您的模型,只需添加此项就可以获得问题的次数:

 LEFT OUTER JOIN (
            SELECT ra.question_id, COUNT(*) AS TotalAnswers
            FROM dbo.form_response_answers ra
            GROUP BY ra.question_id 
        ) G2

然后就像你用G一样加入并获得TotalAnswers。 这很简单......所以我很有可能错过了一些东西:)