0

我有以下数据库设计:

Answers Table: AnswerID, Answer
QuestionAnswers Table: ID, QuestionID, AnswerID
CompleteSurvey Table: ID, QuestionAnswersID, RespondantID
Questions Table: QuestionID, Question
Employee Table: EmployeeID, Name

在其中一个问题中,我有以下答案:

ER Estimate
Company Esitmate
Both ER & Company Estimates
None

这个问题的答案会影响两个问题。我现在想要的是排除选择(无)的员工,然后将他们排除在其他两个问题的参与者人数之外。So how to do that? 让我们假设我们有三个问题,即 A、B 和 C。那么,我将如何从参与问题 B 的员工人数中排除选择(无)作为问题 A 答案的人,以及C。

我编写的查询向我显示了每个问题的每个可能答案中的参与者数量,并且效果很好,但是我如何改进它以获得我想要的以上内容:

SELECT     COUNT(DISTINCT dbo.CompleteSurvey.RespondantID) AS [Total Number of Participants], dbo.Answers.Answer, dbo.Questions.Question
FROM         dbo.Questions INNER JOIN
                      dbo.QuestionsAnswers ON dbo.Questions.QuestionID = dbo.QuestionsAnswers.QuestionID INNER JOIN
                      dbo.Answers ON dbo.QuestionsAnswers.AnswerID = dbo.Answers.AnswerID LEFT OUTER JOIN
                      dbo.CompleteSurvey ON dbo.QuestionsAnswers.ID = dbo.CompleteSurvey.QuestionsAnswersID
GROUP BY dbo.Answers.Answer, dbo.Questions.Question

更新 2:

148 Both ER & Company Estimates
102 Company Estimate
22  ER Estimate  
130 None

问题 A 的每个可能答案的参与者人数。现在对于问题 B,假设我们有以下答案和参与者人数:

22    Answer A
180   Answer B
180   Answer C
20    Answer D

当我应用您的查询从以下问题中排除问题 A 中答案为(无)的人时,我得到问题 B 中所有答案的负数。怎么会这样?

4

1 回答 1

1

也许这可能有效:

SELECT c.Answer, a.Question, COUNT(DISTINCT d.RespondantID) AS totalcount
FROM Questions a
INNER JOIN QuestionAnswers b ON a.QuestionID = b.QuestionID
INNER JOIN Answers c ON b.AnswerID = c.AnswerID
LEFT JOIN CompleteSurvey d ON b.ID = d.QuestionAnswersID
LEFT JOIN
(
    SELECT DISTINCT RespondantID
    FROM CompleteSurvey
    WHERE QuestionAnswersID IN (<id>, <id>)
) e ON d.RespondantID = e.RespondantID
WHERE e.RespondantID IS NULL
GROUP BY c.Answer, a.Question

您必须事先知道ID要排除的问答组合,并将其插入<id>查询中的位置。

于 2012-07-11T05:35:14.023 回答