这是“答案”表。我需要为给定的AcademicYear和TestNo的每个部分计算QuestionNo,即“R”,“W”,“”。什么是最好的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..
很抱歉没有第一次正确填写这个问题。
答案 0 :(得分:3)
修改强>
我在输出中添加了一些列,以便与您的问题更加一致。
只需更换???用你想要的值。
SELECT section, question, answer, COUNT(*) AS count
FROM table
WHERE academicYear = ??? AND testNo = ???
GROUP BY section, question, answer
答案 1 :(得分: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