0

我有以下查询,它返回一个结果集,其中包含问题、这些问题的可能答案以及用户选择每个答案的次数:

SELECT  sq.question_id, sq.question_text, qo.question_option_id, qo.option_text, G.Total
FROM    dbo.survey_question sq
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
sq.question_id

在这些记录中的每一个上,我都需要为 form_id 添加一个列,该列位于名为 form_question 的表中。form_question 表还包含一个 question_id 字段,该字段应与上面查询中显示的 question_id 字段匹配。但是,我在尝试添加它时遇到了很多麻烦,因为我仍在为我的查询而苦苦挣扎。有人可以帮我解决这个问题吗?

4

1 回答 1

2

更改在评论中。

SELECT  
    sq.question_id
    , sq.question_text
    , qo.question_option_id
    , qo.option_text
    , G.Total
-- ==================================================
    , fq.form_id
-- ==================================================
FROM dbo.survey_question sq
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
-- ==================================================
-- Switch this to LEFT JOIN if there is a chance that
-- there won't be a form_question result for your
-- survey_question record.
-- Also, if there are multiple form_question records
-- for a survey_question, you might get more rows than
-- you're looking for.
INNER JOIN dbo.form_question fq
    ON fq.question_id = sq.question_id
-- ==================================================
ORDER BY sq.question_id
于 2012-04-09T16:28:35.020 回答