简体   繁体   中英

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.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM