排序正规和不定期学生的学生

时间:2017-09-02 12:25:19

标签: mysql if-statement

我想选择那个没有成绩不合格的学生。

 Stud_id   grade_1    grade_2    grade_3    RATE
  123        1.5       3.00        2.00    regular
  234        2.00      1.50        5.00    irregular   
  567        3.00      2.00        2.00    regular

选择COUNT(stud_id)等级1和3之间的等级并且没有等级IN(0,5)。

我获得所有普通学生的代码就是这个。

 SELECT COUNT(DISTINCT stud_id FROM grade
 WHERE grade BETWEEN 1 AND 3 AND stud_id ='$student')

但我的问题是,成绩不合格的学生也会计算,因为他也通过了其他年级。

Sample mysql picture

如图所示,ID ='67453432'的学生应该只是出现“REGULAR”状态的学生,因为他没有任何失败的成绩。而另一名学生将因为他们有一个或多个不及格而成为“不规则”。

结果应该是这样的

 EXAMPLE ONLY!!!
    if grade BETWEEN 1 AND 3 AND Dont have 0.00 OR 5.00 = REGULAR
     BUT if GRADE BETWEEN 1 AND 3 AND HAVE 0.0 OR 5.00 = IRREGULAR

    Stud_ID   RATE
    67453432 REGULAR
     123     REGULAR
     234     IRREGULAR
     567     REGULAR

1 个答案:

答案 0 :(得分:0)

您可以通过以下查询获得不规则学生:

SELECT stud_id, 'Irregular'
FROM students
WHERE grade IN (0,5);

和普通学生通过以下查询:

SELECT stud_id, 'Regular'
FROM students
WHERE grade BETWEEN 1 AND 3
AND stud_id NOT IN (
    SELECT stud_id
    FROM students
    WHERE grade IN (0,5)
);

现在,您可以UNION这两个查询来获得结果,例如:

SELECT stud_id, 'Irregular'
FROM students
WHERE grade IN (0,5)

UNION

SELECT stud_id, 'Regular'
FROM students
WHERE grade BETWEEN 1 AND 3
AND stud_id NOT IN (
    SELECT stud_id
    FROM students
    WHERE grade IN (0,5)
);