2011-06-09 146 views
1

這裏是我想我的結果看起來像:SQL返回從0的答案爲其他表的選擇

編輯!更多有用結構提供here

Answer Counts 
------ ------- 
0  0 
1  12 
2  4 
3  0 
4  3 
5  6 

響應存儲爲1,2,3,4,5其中每個n = A,B,C,d或類似的東西。

我的問題是

SELECT COUNT(answer_sequence) AS 'Answer Count' 
FROM tblILDSlideResponses 
WHERE response_id IN (
    SELECT id 
    FROM tblILDSlideResponseInfo 
    WHERE (slide_id = @slide) AND (session_id = @sessionid) 
) 
GROUP BY answer_sequence 

返回事情是這樣的:

Answer Counts 
------ ------- 
0  12 
1  4 
2  3 
3  6 

所以當有可能的選擇,沒有答案,我沒有得到任何計數。 所以我知道我要抓住可能的選擇,其可在這裏:

SELECT Choice AS 'Choices' 
FROM tblSurveyAnswerChoices 
WHERE QID IN (
    SELECT question_id 
    FROM tblILDSlide 
    WHERE id = @slide 
) 

然後以某種方式將它們映射到答案。但是,我將如何實現這一點,並保持這些順序。我想我需要爲tblSurveyAnswerChoices中存在的每個答案返回一個空行然後以某種方式加入其他計數,但我無法弄清楚。

編輯!

在響應請求從@ Christopherous5000:

dbo.tblSLideResponseInfo 
id (PK,int,not null) 
user_id (nvarchar(50), not null) --will be FK eventualy 
slide_id (FK,int, not null) 
response_date (datetime, not null) 
session_id (FK,int,not null) 

dbo.tblSLideResponses --can store multiple answer for same response 
response_id (FK,int,not null) 
answer_sequence(int, null) 
pther (nvarchar(50), null) 
+1

請添加表結構爲tblILDSlideResponses和tblILDSlideResponseInfo – 2011-06-10 00:01:00

+0

@ Christopherous5000他更新了問題btw。 – jcolebrand 2011-06-12 18:13:04

回答

2

您的文章中已經包含一個很好的答案:「我想我需要返回一個空一行,在tblSurveyAnswerChoices存在,那麼每個答案以某種方式加入其他計數。「

這裏是這樣做的一個辦法:

select choice, ifnull(countanswervalue,0) 
from tblsurveyanswerchoice 
left join 
    (select answer_sequence, count(answer_sequence) as countanswervalue 
    from tblslideresponses 
    group by answer_sequence) 
    as countanswer on countanswer.answer_sequence=tblsurveyanswerchoice.sequence 
/* the where clause is what you already posted */ 
where qid in (select question_id from tblidslide where id = @slide) 

採用left join確保在第一表中的任何選擇將陸續上市。默認情況下,左連接將返回NULL在第二個表不存在的項目,但ifnull讓您以0

注意替換NULL:ifnull在MySQL應該isnull在TSQL更換

0

我的問題是

SELECT COUNT(answer_sequence) AS 'Answer Count' 
FROM tblILDSlideResponses 
WHERE response_id IN (
     SELECT id FROM tblILDSlideResponseInfo 
     WHERE (slide_id = @slide) AND (session_id = @sessionid) 
    ) 
GROUP BY answer_sequence 

(...),所以當有一個可能的選擇有沒有答案,我得到沒有數量。所以我知道我需要抓住這裏可能的選擇。

或者,你可以嘗試使用left join

SELECT answer_sequence, COUNT(answer_sequence) AS 'Answer Count' 
FROM tblILDSlideResponses 
LEFT JOIN tblILDSlideResponseInfo 
ON (slide_id = @slide) AND (session_id = @sessionid) 
AND tblILDSlideResponseInfo.id = tblILDSlideResponses.response_id 
GROUP BY answer_sequence 
+0

「無效」是什麼意思?如果您只計算一次,它會返回收到的答案總數。將計數和分組結合起來可以計算出個人答案,這正是我所需要的。上述建議僅返回與以前相同的響應。它不會爲tblSurveyAnswerChoices中的每個可用答案添加零。 – gooddadmike 2011-06-10 14:42:33

+1

對不起。我忘了編輯它。它實際上是有道理的 - 它基本上就像計數(1)或計數(*)一樣。 – 2011-06-10 14:44:32