MySql为条件计数

时间:2012-05-11 13:54:26

标签: mysql database

输入是:

+--------+-------+----------+----------+
| RESULT | EXMID | EXSUBJID | SID      |
+--------+-------+----------+----------+
|     11 |     4 |        6 | Student4 |
|     12 |     4 |        6 | Student3 |
|     25 |     4 |        6 | Student5 |
|     45 |     4 |       10 | Student8 |
|     12 |     4 |       10 | Student4 |
|    100 |     4 |       10 | Student5 |
|     12 |     4 |       10 | Student3 |
+--------+-------+----------+----------+

我有这张表,其中列出了出现在不同科目的特定考试中的学生。

总科目是考试科目的总数。通过代表学生在任何科目中通过的状态,而失败代表学生在任何科目中失败的状态。

现在问题是考试中学生的通过,失败和通过百分比的总数。如果学生在任何科目上失败,他/她就会失败。

我尝试过很多东西,却无法得到结果。

这就是我得到的:

+----------+------------+------+------+--------------+
| STUDENT  | TOTAL_SUBJ | PASS | FAIL | PASS_PERCENT |
+----------+------------+------+------+--------------+
| Student3 |          2 |    1 |    1 |        50.00 |
| Student4 |          2 |    0 |    2 |         0.00 |
| Student5 |          2 |    2 |    0 |       100.00 |
| Student8 |          2 |    1 |    0 |       100.00 |
+----------+------------+------+------+--------------+

任何人都可以为它提供一个好的解决方案吗?

以下是我对上述输出的查询。

SELECT DISTINCT exreslt.SID AS STUDENT,
COUNT(exsubj.EXSUBJID) AS TOTAL_SUBJ,
SUM(exreslt.RESULT >= exsubj.PASS) AS PASS,
SUM(exreslt.RESULT < exsubj.PASS) AS FAIL,

ROUND(SUM(exreslt.RESULT >= exsubj.PASS)*100/ COUNT(exreslt.SID),2) AS 'PASS_PERCENT'
FROM EXAMSUBJ AS exsubj
STRAIGHT_JOIN EXAMRESULT AS exreslt
WHERE exsubj.EXSUBJID = exreslt.EXSUBJID AND exsubj.EXMID = exreslt.EXMID AND exsubj.EXMID=4 GROUP BY exreslt.SID ;

我希望输出为

+----------+------------+------+------+--------------+
| STUDENT  | TOTAL_SUBJ | PASS | FAIL | PASS_PERCENT |
+----------+------------+------+------+--------------+
|       4  |          2 |    2 |    2 |        50.00 |
+----------+------------+------+------+--------------+

如果任何学生在任何一个科目中失败,他将被视为失败,否则他将被通过。

0 个答案:

没有答案