[英]Count and sum from table
我有下表,我需要获得在考试中获得A的学生人数。 这是我想从下表中实现的:
3 A = 0学生。 2 A = 3名学生。
+--------------+------------+------+
| student_ID | kod_subjek | gred |
+--------------+------------+------+
| 746123096687 | 02 | A |
| 746123096687 | 12 | B |
| 746123096687 | 21 | A |
| 860206145454 | 12 | A |
| 860206145454 | 02 | A |
| 881012085535 | 02 | A |
| 881012085535 | 21 | A |
+--------------+------------+------+
我试着用:
mysql> SELECT student_ID, COUNT(gred) FROM data_exam GROUP BY student_ID;
输出是:
+--------------+-------------+
| student_ID | COUNT(gred) |
+--------------+-------------+
| 746123096687 | 3 |
| 860206145454 | 2 |
| 881012085535 | 2 |
+--------------+-------------+
它不起作用。 它只会计算特定学生的所有成绩。 请帮我解决这个问题。 谢谢。
SELECT a_count, COUNT(*) AS cnt
FROM
(
SELECT COUNT(*) AS a_count
FROM data_exam
WHERE gred = 'A'
GROUP BY student_id
) x
GROUP BY a_count
ORDER BY a_count
关于SQL-Fiddle返回的示例 :
a_count cnt
2 3
您可以使用子查询:
SELECT num_as, COUNT(1) AS num_students
FROM (
SELECT student_ID, COUNT(gred) AS num_as
FROM data_exam
WHERE gred = 'A'
GROUP BY student_ID
) counts_by_student
GROUP BY num_as
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.