2010-10-27 187 views
0

以下是表格「Answers」。對於給定的AcademicYear和TestNo,我需要對每個部分的「R」,「W」,「」QuestionNo計數。什麼是最好的SQL查詢?SQL查詢問題

AcademicYear StudentID TestNo Section QuestionNo Answer 

2010-2011  1  1  2  1  R 
2010-2011  1  1  2  2  W 
2010-2011  1  1  2  3  R 
2010-2011  1  1  2  4   
2010-2011  1  1  2  5   
2010-2011  1  1  2  6   
2010-2011  1  1  2  7   
2010-2011  1  1  2  8   
2010-2011  1  1  2  9   
2010-2011  1  1  2  10   

最終的結果應該是這樣的:

Section QuestionNo Answer Count 
    2   1   R  15 
    2   1   W  25 
    2   1     100 
    2   2   R  10 
    2   2   W  50 
    2   2     10 
    etc.. 

對不起,不framming問題正確的首次。

回答

3

編輯

我加了一些列的輸出要與你的問題更一致。

只需更換???與你想要的值。

SELECT section, question, answer, COUNT(*) AS count 
FROM table 
WHERE academicYear = ??? AND testNo = ??? 
GROUP BY section, question, answer 
2
select 
academicyear, testno, 

sum(case when answer='R' then 1 else 0 end) as Right, 
sum(case when answer='W' then 1 else 0 end) as Wrong 
from 
T 
group by academicyear, testno 
+1

還添加了一個案例 '' 或爲空 – Mike 2010-10-27 17:37:18