0
我有一個非常複雜的select語句,它使用內部聯接從表中返回統計表(將其視爲答案庫 - 下面的複雜選擇語句)。嵌套選擇或內部聯接包括來自另一個表的行
這些答案與名爲Questions_Bank_AnswerChoices(存儲所有問題)的表相關。
我試圖首先從問題(從表Questions_Bank_AnswerChoices)中提取問題,然後將它們與統計信息(下面的複雜語句)進行匹配。下面的複雜聲明拉動了統計數據,但除非得到答案,否則不會提出問題。
因此,如果沒有人回答question1,那麼問題一將不會顯示在統計數據中,因爲它不包含在答案表中(bc沒有人回答它)。
我該如何做到這一點?我認爲我需要外連接?
複雜的SELECT語句:
WITH tbl as (
SELECT
Questions_Bank.QuestionID, Questions_Bank.QuestionName,
REPLACE(Schools_Answers_Items.AnswerValue, '? ', ', ') as AnswerValue,
COUNT(Schools_Answers_Items.SchoolsAnswersItemID) AS CountAnswer,
Schools_Answers_Items.SchoolID
FROM Questions_Bank
INNER JOIN Schools_Answers_Items
ON Questions_Bank.QuestionID = Schools_Answers_Items.QuestionID
LEFT OUTER JOIN Schools_Answers
ON Schools_Answers_Items.SchoolsAnswerID = Schools_Answers.SchoolsAnswerID
WHERE (Questions_Bank.QuestionID = 1108)
AND (Schools_Answers.SchoolID = 103)
GROUP BY
Schools_Answers_Items.SchoolID,
Schools_Answers_Items.AnswerValue,
Questions_Bank.QuestionID,
Questions_Bank.QuestionName
)
SELECT
QuestionID, QuestionName, AnswerValue, CountAnswer,
SUM(CountAnswer) OVER() AS CountAllAnswers
FROM tbl
這並不工作,但我認爲我們是在正確的軌道上。該行:「ON Questions_Bank.QuestionID = Schools_Answers_Items.QuestionID」用這麼多詞彙表示只在該情況下加入(但有時Schools_Answers_Items.QuestionID不存在,因爲它沒有被回答),但我確實認爲外部會修復它? – user1601804 2012-08-16 19:23:52
LEFT OUTER JOIN應包含JOIN左邊部分表格中的所有內容,在本例中爲Questions_Bank。我會將計數字段和分組取下來,然後嘗試一下「WHERE SchoolID IS NULL」以查看是否在沒有學校答案的情況下提出任何問題。 – Jim 2012-08-16 19:49:02