1

我有以下查询,它返回问题列表和每个问题的可能答案:

SELECT
sq.question_id, sq.question_text, qo.question_option_id, qo.option_text

FROM
 dbo.survey_question sq
LEFT OUTER JOIN dbo.question_option qo on sq.question_id = qo.question_id

ORDER BY
sq.question_id

我还有以下查询,它返回选择了特定答案的次数:

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 

我需要组合这两个查询,以便返回的结果列出所有问题/可能的答案(如第一个查询)以及选择该答案的次数。

我尝试从第二个查询中创建一个 VIEW 并从第一个查询到第二个查询执行几个 OUTER JOINS,但我无法使其工作。有人会指出我正确的方向吗?

4

1 回答 1

1

试试这个:

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 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
于 2012-04-09T13:58:24.707 回答