Reputation: 1
I have a table for exam result, how can I filter and count my "correct" values on my table and somehow group them by User Number and Module? for example, i only want to count my "correct" values:
Upvotes: 0
Views: 63
Reputation: 18737
Two alternatives:
Using 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
Result:
USERNO QUESTIONRESULT MODULE
123456 3 1
987456 2 1
123456 4 2
987456 1 2
See result in SQL Fiddle.
Using WHERE
caluse:
SELECT UserNo,
COUNT(QuestionResult) as QuestionResult,
ModuleNo as Module
FROM TableName
WHERE QuestionResult = 'Correct'
GROUP BY `UserNo`,ModuleNo
ORDER BY ModuleNo,UserNo
See result in SQL Fiddle.
Upvotes: 1
Reputation: 44581
First solution using SUM
and CASE
SELECT `UserNo` ,
SUM(CASE WHEN `QuestionResult` = 'Correct' THEN 1 ELSE 0 END) AS QuestionResultCount ,
`Module`
FROM `TableName`
GROUP BY `UserNo` ,
`Module`
Second solution using COUNT
and WHERE
clause :
(Note: This could be better for large tables with proper indexes, since the DBE can use that index to filter the table while it can not be done with any CASE..WHEN
based solutions.)
SELECT `UserNo` ,
COUNT(`QuestionResult`) AS QuestionResultCount ,
`Module`
FROM `TableName`
WHERE `QuestionResult` = 'Correct'
GROUP BY `UserNo` ,
`Module`
Third solution using COUNT
and CASE
:
SELECT `UserNo` ,
COUNT(CASE WHEN `QuestionResult` = 'Correct' THEN `QuestionResult` END) AS QuestionResultCount ,
`Module`
FROM `TableName`
GROUP BY `UserNo` ,
`Module`
Upvotes: 1
Reputation: 6877
Use COUNT
SELECT UserNo,
COUNT(QuestionResult)
FROM TABLE
WHERE QuestionResult = 'Correct'
GROUP BY ModuleNo, ModuleNo
Upvotes: -1
Reputation: 3497
SELECT
UserNo, ModuleNo, COUNT(QuestionResult) as correctanswers
FROM yourtablename
WHERE
QuestionResult='Correct'
GROUP BY
UserNo, ModuleNo
You have to group twice if you want it grouped by the user and the module.
Upvotes: 1