需要mysql查询才能在单个查询中获得学生PASS,FAIL和COUNT

时间:2011-02-18 14:35:02

标签: mysql

我有一张桌子如下:

id    studentName   Marks

1        X           60

2        Y           25

3        Z           50

此处传球标记为50及以上

我的输出应该是

id    studentName   Marks  status  totalCount

1        X           60     PASS       2

2        Y           25     FAIL       1

3        Z           50     PASS       2

此处传球总数为2,失败总数为1。

如何使用MYSQL QUERY完成此操作。

提前感谢....

3 个答案:

答案 0 :(得分:2)

SELECT A.id,A.studentName,A.Marks,B.status,B.totalStatus
FROM students A,
    (SELECT COUNT(1) totalStatus,IF(Marks>=50,'PASS','FAIL') status 
       FROM students GROUP BY IF(Marks>=50,'PASS','FAIL')) B
WHERE B.status = IF(A.Marks>=50,'PASS','FAIL');

这真的有效!我实际上试过了!!!

lwdba @ localhost(DB test2):: CREATE TABLE学生
     - > (
     - > id INT NOT NULL,
     - > studentName VARCHAR(10),
     - >标记INT NOT NULL,
     - >主要钥匙(id)
     - > );
查询OK,0行受影响(0.17秒)

lwdba @ localhost(DB test2):: INSERT INTO students VALUES
     - > (1, 'X',60),
     - > (2, 'Y',25),
     - > (3, 'X',50);
查询OK,3行受影响(0.06秒)
记录:3个重复:0警告:0

lwdba @ localhost(DB test2):: SELECT A.id,A.studentName,A.Marks,B.status,B.totalStatus
     - >来自学生A,(SELECT COUNT(1)totalStatus,IF(Marks> = 50,'PASS','FAIL')状态
来自学生GROUP BY IF(Marks> = 50,'PASS','FAIL' ))B
     - >在哪里B.status = IF(A.Marks> = 50,'PASS','FAIL');
+ ---- + ------------- + ------- + -------- + ------------- +
| id | studentName |标记|状态| totalStatus |
+ ---- + ------------- + ------- + -------- + ------------- +
| 1 | X | 60 |通过| 2 |
| 2 | Y | 25 |失败| 1 |
| 3 | X | 50 |通过| 2 |
+ ---- + ------------- + ------- + -------- + ------------- +
3行(0.00秒)

试一试!!!

答案 1 :(得分:2)

select s.id, s.studentName, s.Marks,
       case when s.Marks >= 50 then 'Pass' else 'Fail' end as Status,
       case when s.Marks >= 50 then t.TotalPass else t.TotalFail end as TotalCount
    from @Students s,
         (select SUM(case when Marks >= 50 then 1 else 0 end) as TotalPass,
                 SUM(case when Marks < 50 then 1 else 0 end) as TotalFail
              from @Students) t

答案 2 :(得分:0)

使用“case”语句将#'s转换为“pass”,“fail。将其与group by和count(*)组合。我不清楚”标记“和”总状态“是什么哪一个是成绩?哪一个是成绩?

http://dev.mysql.com/doc/refman/5.0/en/case-statement.html