我有一个非常复杂的select语句,它使用内连接从表中返回计数统计信息(将其视为答案库 - 下面的复杂选择语句)。
这些答案与一个名为Questions_Bank_AnswerChoices(存储所有问题)的表相关。
我试图首先提出问题(来自Question_Bank_AnswerChoices表),然后将它们与统计数据(下面的复杂语句)进行匹配。下面的复杂陈述会提取统计数据,但除非已经回答,否则不会提出问题。
所以,如果没有人回答问题1,那么问题一不会出现在统计数据中,因为它没有包含在Answers表中(bc没有人回答)。
我怎样才能做到这一点?我认为我需要外联?
复杂选择声明:
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
答案 0 :(得分:1)
尝试更改此
INNER JOIN Schools_Answers_Items
ON Questions_Bank.QuestionID = Schools_Answers_Items.QuestionID
到
LEFT OUTER JOIN Schools_Answers_Items
ON Questions_Bank.QuestionID = Schools_Answers_Items.QuestionID
您可能想删除此
AND (Schools_Answers.SchoolID = 103)
或用此
替换它AND (Schools_Answers.SchoolID = 103 OR Schools_Answers.SchoolID IS NULL)
试试这个:
SELECT
Questions_Bank.QuestionID, Questions_Bank.QuestionName,
REPLACE(Schools_Answers_Items.AnswerValue, '? ', ', ') as AnswerValue,
Schools_Answers_Items.SchoolID
FROM Questions_Bank
LEFT OUTER 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 Schools_Answers_Items.SchoolID