在mysql中分组时从状态获取学生结果

时间:2018-07-05 08:09:05

标签: mysql group-by

我已经从记录创建了一个临时表,如下所示。我想使用学生证(stu_D)对学生进行分组。在分组学生时,如果他通过了所有主题,则状态为“通过”,如果他至少一项不及格,则为“失败”。

enter image description here

3 个答案:

答案 0 :(得分:1)

您可以在下面的查询中尝试-

 SELECT stu_D
   ,stuName
   ,CASE 
    WHEN T2.CNT = 0 
         THEN 'passed' 
         ELSE 'failed' 
    END status 
FROM (SELECT stu_D
            ,stuName
            ,COUNT(CASE
                   WHEN result = 'FAILED' 
                       THEN 1
                   END) CNT
     FROM T
     GROUP BY stu_D
             ,stuname) T2

答案 1 :(得分:0)

SELECT 
   T.stu_D, T.stuName, IF(T.number_of_failures>0, 'FAILED', 'PASSED') final_result
FROM
(SELECT 
   stu_D, stuName, COUNT(IF(result='FAILED', 1, NULL)) number_of_failures
 FROM your_table
 GROUP BY stu_D, stuName) T;

答案 2 :(得分:0)

尝试此查询

 SELECT stu_Name,result
    FROM `marks`
    WHERE stu_D not in
    (SELECT stu_D FROM marks WHERE  result='FAILED')
    GROUP BY stu_D