I have record of students, every day they undertakes a driving test =, I would like to calculate total number of students who have passed and failed their driving test for today's date eg
StudentName Status date pass fail
test1 something 2014-05-14 1 0
test2 something 2014-05-14 0 1
test1 something 2014-04-14 0 1
test1 something 2014-03-14 0 1
At the moment I have this query - select count(case pass where 1 then 1 else null end) As TotalPassed, count(case pass where 1 then 1 else null end) as Totalfailed from DatabaseName where date>='2014-05-14'
The problem is this query only search for total record from 2014-05-14, but what I want is total number of record for a specific student. For this query I get result as;
StudentName Status date pass fail
test1 Something 2014-05-14 1 0
test2 something 2014-05-14 0 1
But what I need is the query to calculate the total number of time that each person have passed or failed his/her exams, so the expected result should be:
StudentName Status date pass fail
test1 something 2014-05-14 1 2
test2 something 2014-05-14 0 1
You should use SUM
instead of COUNT
, and add a GROUP BY
in the end.
SELECT StudentName,
MAX(date) as date,
SUM(pass) As TotalPassed,
SUM(fail) As Totalfailed,
SUM(pass) + SUM(fail) as TotalTriesVersion1,
COUNT(*) as TotalTriesVersion2
FROM Table1
GROUP BY StudentName
And here is the sqlfiddle (next time, please provide it yourself :) )
Bonus : I gave you two ways of computing the total number of time each student has taken the exam, as I understood from the comments that you wanted to have this too.
You need to use the GROUP BY Clause like this:
SELECT COUNT(CASE pass WHERE 1 THEN 1 ELSE NULL END) AS TotalPassed,
COUNT(CASE pass WHERE 1 THEN 1 ELSE NULL END) AS Totalfailed FROM DatabaseName
WHERE date>='2014-05-14' GROUP BY StudentName
select studentname , date , sum(pass) as Totalpass, sum(fail) as TotalFail from DatabaseName where date ='2014-05-14'
group by studentname,date
try it with a group by
select StudentName, date, sumpass, fail, count(*) from table group by StudentName, date, pass, fail
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.