在SQL Server 2005中组合来自两个查询的数据

时间:2012-04-09 13:52:53

标签: sql-server-2005

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

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,但我无法使其工作。有人会指出我正确的方向吗?

1 个答案:

答案 0 :(得分: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