问题
I have a table which consists of the following
Student Name Grade Class
--------------------------------------------------------
User 1 A English
User 1 B Math
User 2 B Math
I'm trying to create a query where it will list all students, total pass grades (grades A,B & C), total A's, Total B's, Total C's
Can someone help me create the query or atleast put me in the right direction?
回答1:
Give this a try:
select name,
count(case when grade in ('A', 'B', 'C') then 1 end) totalPass,
count(case when grade = 'A' then 1 end) totalA,
count(case when grade = 'B' then 1 end) totalB,
count(case when grade = 'C' then 1 end) totalC
from t
group by name
Here is the fiddle.
Or we can make it even simpler if you were using MySQL:
select name,
sum(grade in ('A', 'B', 'C')) totalPass,
sum(grade = 'A') totalA,
sum(grade = 'B') totalB,
sum(grade = 'C') totalC
from t
group by name
Here is the fiddle.
回答2:
You should use sum instead of count, and use a conditional expression inside, like this:
select
sum(case when grade in ('A','B','C') then 1 else 0 end) as passing
, sum(case when grade = 'A' then 1 else 0 end) as NumA
, sum(case when grade = 'B' then 1 else 0 end) as NumB
, sum(case when grade = 'C' then 1 else 0 end) as NumC
from grades
This example is for SQL Server (see sqlfiddle here), but other RDBMSs have similar capabilities.
回答3:
Yet another possible answer (very long but self explanatory):
select u.UserName
,totalA = count(a.Grade)
,totalB = count(b.Grade)
,totalC = count(c.Grade)
,totalPass = count(p.Grade)
from
GradeUser u
LEFT JOIN GradeUser a on a.UserName = u.UserName
AND a.Grade = u.Grade AND a.Class = u.Class
AND a.Grade ='A'
LEFT JOIN GradeUser b on b.UserName = u.UserName
AND b.Grade = u.Grade AND b.Class = u.Class
AND b.Grade ='B'
LEFT JOIN GradeUser c on c.UserName = u.UserName
AND c.Grade = u.Grade AND c.Class = u.Class
AND c.Grade ='C'
LEFT JOIN GradeUser p on p.UserName = u.UserName
AND p.Grade = u.Grade AND p.Class = u.Class
AND p.Grade IN ('A', 'B', 'C')
GROUP BY u.UserName
回答4:
Here is a solution in Access SQL, in two separate queries:
Number of total pass grades per student:
SELECT grades.StudentName, Count(grades.Grade) AS NumberOfPassGrades
FROM grades
WHERE (((grades.Grade) In ('A','B','C')))
GROUP BY grades.StudentName
ORDER BY grades.StudentName;
Number of total A's, Total B's, Total C's:
SELECT grades.StudentName, grades.Grade, Count(grades.Grade) AS NumberOfGrades
FROM grades
GROUP BY grades.StudentName, grades.Grade
ORDER BY grades.StudentName, grades.Grade;
If you really need only one query, the easiest way to do this would be to save both queries as Access queries and join them on StudentName. However, then you would get the NumberOfPassGrades more than once as soon as a student has more than one different grade.
来源:https://stackoverflow.com/questions/10240035/sql-and-counting