-2

我有一张表,其中包含以下内容

Student Name        Grade       Class
--------------------------------------------------------
User 1              A           English
User 1              B           Math
User 2              B           Math

我正在尝试创建一个查询,它将列出所有学生、总及格分数(A、B 和 C 级)、总 A、总 B、总 C

有人可以帮我创建查询或至少让我朝着正确的方向前进吗?

4

4 回答 4

3

您应该使用sum而不是count,并在内部使用条件表达式,如下所示:

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

此示例适用于 SQL Server (请参阅此处的 sqlfiddle),但其他 RDBMS 具有类似的功能。

于 2012-04-20T04:08:13.853 回答
3

试试这个:

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

这是小提琴

或者,如果您使用的是 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

这是小提琴

于 2012-04-20T04:08:39.177 回答
0

这是 Access SQL 中的一个解决方案,在两个单独的查询中:

每个学生的总及格分数:

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;

A 总数、B 总数、C 总数:

SELECT grades.StudentName, grades.Grade, Count(grades.Grade) AS NumberOfGrades
FROM grades
GROUP BY grades.StudentName, grades.Grade
ORDER BY grades.StudentName, grades.Grade;

如果您真的只需要一个查询,最简单的方法是将这两个查询保存为 Access 查询并将它们加入 StudentName。但是,一旦学生有多个不同的成绩,您就会多次获得 NumberOfPassGrades。

于 2012-04-20T05:20:57.193 回答
0

另一个可能的答案(很长但不言自明):

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
于 2012-04-20T04:26:13.037 回答