2012-04-09 82 views
1

我有以下查詢返回的問題的列表,併爲每個問題可能的答案:從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

試試這個:

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