如何从基于另一个表的表中计数

时间:2012-12-26 21:19:58

标签: sql join count

我有4个表,我不需要'问题'表,但我只是把它放在那里,所以你知道我在哪里得到了其他表中的问题ID。

Questions
--------
ID 
Question


Question_Options
--------
ID 
Question_ID
Option_Label


Session
--------------
ID    
GENDER   


Session_Answers
-----------------
ID
Session_ID
Option_ID
Question_ID

我计算了以下内容:来自某个问题的每个选项的投票数,如此

SELECT Q.Option_Label as Choice, COALESCE((SELECT COUNT(*) FROM Session_Answers S WHERE S.Option_ID = Q.ID),0) as Votes
FROM Question_Options Q 
     INNER JOIN Session_Answers S
       ON Q.Question_ID = S.Question_ID
WHERE Q.Question_ID = 10114<---the Question ID
GROUP BY Q.ID,Q.option_label

我想要做的是在查询中添加一个新列,用于计算根据会话表选择每个选项的男性数量。

2 个答案:

答案 0 :(得分:0)

您只需在使用Gender过滤的会话表中添加额外的计数。

SELECT Q.Option_Label as Choice, COALESCE((SELECT COUNT(*) FROM Session_Answers SA WHERE
SA.Option_ID = Q.ID),0) as Votes,
COALESCE((SELECT COUNT(*) FROM Session SM WHERE
S.Session_ID = SM.Session_ID AND Gender='M'),0) as MalesSessions
FROM Question_Options Q 
    INNER JOIN Session_Answers S
    ON Q.Question_ID = S.Question_ID
WHERE Q.Question_ID = 10114 ---the Question ID
GROUP BY Q.ID,Q.option_label

答案 1 :(得分:0)

你可以这样做:

SELECT QO.Question_ID, QO.Option_Label as Choice, COUNT(*) as VotesMale
FROM Question_Options QO 
LEFT JOIN Session_Answers SA ON QO.ID = SA.Option_ID
JOIN [Session] S ON S.ID = SA.Session_ID AND S.Gender = 'M'
WHERE QO.Question_ID = 10114<---the Question ID
GROUP BY QO.Question_ID, QO.Option_label