我有如下表格:
id studentName Marks
1 X 60
2 Y 25
3 Z 50
这里pass Marks是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 完成此操作。
提前致谢....
最佳答案
SELECT A.id, A.studentName, A.Marks, B.status, B.totalStatus
FROM students AS A,
(SELECT COUNT(1) AS totalStatus,
IF(Marks>=50, 'PASS', 'FAIL') AS status
FROM students
GROUP BY IF(Marks>=50, 'PASS', 'FAIL')
) AS B
WHERE B.status = IF(A.Marks>=50, 'PASS', 'FAIL');
-- lwdba@localhost (DB test2) ::
CREATE TABLE students
(
id INT NOT NULL,
studentName VARCHAR(10),
Marks INT NOT NULL,
PRIMARY KEY (id)
);
-- Query OK, 0 rows affected (0.17 sec)
-- lwdba@localhost (DB test2) ::
INSERT INTO students VALUES
(1, 'X', 60),
(2, 'Y', 25),
(3, 'X', 50);
-- Query OK, 3 rows affected (0.06 sec)
-- Records: 3 Duplicates: 0 Warnings: 0
-- lwdba@localhost (DB test2) ::
SELECT A.id, A.studentName, A.Marks, B.status, B.totalStatus
FROM students AS A,
(SELECT COUNT(1) AS totalStatus,
IF(Marks>=50, 'PASS', 'FAIL') AS status
FROM students
GROUP BY IF(Marks>=50, 'PASS', 'FAIL')) AS B
WHERE B.status = IF(A.Marks>=50, 'PASS', 'FAIL');
+----+-------------+-------+--------+-------------+
| id | studentName | Marks | status | totalStatus |
+----+-------------+-------+--------+-------------+
| 1 | X | 60 | PASS | 2 |
| 2 | Y | 25 | FAIL | 1 |
| 3 | X | 50 | PASS | 2 |
+----+-------------+-------+--------+-------------+
3 rows in set (0.00 sec)
关于mysql - 需要 mysql 查询才能在单个查询中获取学生通过、失败和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5042537/