[英]How to compare column values of different rows with SQL
I have a table that contains a list of teachers, the classes they are teaching and how many students passed and how many students failed. 我有一张桌子,其中包含一系列教师,他们正在教授的课程,以及有多少学生通过以及有多少学生失败。
Teacher-ID Class Pass/Fail Count
-------------------------------------------------------
1 English Pass 15
1 English Fail 5
1 Math Pass 20
1 Math Fail 10
2 Science Pass 15
2 Science Fail 10
2 Spanish Pass 20
2 Spanish Fail 8
What I want to do is get a percentage for each teacher and class combination of how many students failed. 我想要做的是获得每个教师和班级组合中有多少学生失败的百分比。
Teacher-ID Class % Failed
-------------------------------------------------------
1 English 25%
1 Math 33%
2 Science 40%
2 Spanish 29%
I am stumped as to how to use SQL to do this. 我很难过如何使用SQL来做到这一点。
Here is the query you can use: 这是您可以使用的查询:
SELECT
TeacherID,
Class,
SUM(CASE WHEN PassFail = 'Fail' THEN Count ELSE 0 END) * 100.0 /SUM(Count) as FailPersent
FROM tbl
GROUP BY TeacherID, Class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.