在二级表上加入和求和?

时间:2014-08-26 14:53:35

标签: sql sql-server sql-server-2012

我有以下两种表结构:

问题表

QuestionID | Response
1              Yes
2              No
1              No

问题查询表

QuestionID | Lookup
1              No
2              No
3              No

我试图获得Lookup和Response相等的总和。例如,QuestionID 1的Lookup值为“No”。在问题表中,有两个QuestionID,其值为1.其中一个响应的值为No,因此我将增加1的返回值,并将最终结果按QuestionID分组。

2 个答案:

答案 0 :(得分:1)

SELECT a.QuestionId, SUM(CASE WHEN(b.Lookup = a.Response) THEN 1 ELSE 0 END) AS [Count]
FROM Questions a
INNER JOIN QuestionLookup b ON a.QuestionId = b.QuestionId
GROUP BY a.QuestionId

答案 1 :(得分:0)

如果你只想看看有多少正确的答案,这就是你所需要的。

SELECT COUNT(*) FROM QuestionLookupTable Q
INNER JOIN Questions R
  ON Q.QuestionID = R.QuestionID
WHERE Q.Lookup = R.Response

如果哪个问题得到了多少正确答案很重要......

SELECT Q.QuestionID, COUNT(*) FROM QuestionLookupTable Q
INNER JOIN Questions R
  ON Q.QuestionID = R.QuestionID
WHERE Q.Lookup = R.Response
GROUP BY Q.QuestionID