我有一张考试成绩表,如何过滤和计算我的"正确"我的桌子上的值,并以某种方式按用户编号和模块分组?例如,我只想数我的"正确"值:
答案 0 :(得分:1)
使用SUM
和CASE
SELECT `UserNo` ,
SUM(CASE WHEN `QuestionResult` = 'Correct' THEN 1 ELSE 0 END) AS QuestionResultCount ,
`Module`
FROM `TableName`
GROUP BY `UserNo` ,
`Module`
使用COUNT
和WHERE
子句的第二个解决方案:
(注意:对于具有适当索引的大型表,这可能更好,因为DBE可以使用该索引来过滤表,而无法使用任何基于CASE..WHEN
的解决方案。)
SELECT `UserNo` ,
COUNT(`QuestionResult`) AS QuestionResultCount ,
`Module`
FROM `TableName`
WHERE `QuestionResult` = 'Correct'
GROUP BY `UserNo` ,
`Module`
使用COUNT
和CASE
的第三种解决方案:
SELECT `UserNo` ,
COUNT(CASE WHEN `QuestionResult` = 'Correct' THEN `QuestionResult` END) AS QuestionResultCount ,
`Module`
FROM `TableName`
GROUP BY `UserNo` ,
`Module`
答案 1 :(得分:1)
SELECT
UserNo, ModuleNo, COUNT(QuestionResult) as correctanswers
FROM yourtablename
WHERE
QuestionResult='Correct'
GROUP BY
UserNo, ModuleNo
如果您希望按用户和模块分组,则必须分组两次。
答案 2 :(得分:1)
两种选择:
使用CASE
:
SELECT UserNo,
SUM(CASE WHEN QuestionResult = 'Correct' THEN 1 ELSE 0 END) as QuestionResult,
ModuleNo as Module
FROM TableName
GROUP BY `UserNo`,ModuleNo
ORDER BY ModuleNo,UserNo
结果:
USERNO QUESTIONRESULT MODULE
123456 3 1
987456 2 1
123456 4 2
987456 1 2
请参阅SQL Fiddle中的结果。
使用WHERE
caluse:
SELECT UserNo,
COUNT(QuestionResult) as QuestionResult,
ModuleNo as Module
FROM TableName
WHERE QuestionResult = 'Correct'
GROUP BY `UserNo`,ModuleNo
ORDER BY ModuleNo,UserNo
请参阅SQL Fiddle中的结果。
答案 3 :(得分:-1)
使用COUNT
SELECT UserNo,
COUNT(QuestionResult)
FROM TABLE
WHERE QuestionResult = 'Correct'
GROUP BY ModuleNo, ModuleNo