从表中计算和求和

时间:2012-10-07 14:02:26

标签: php mysql

我有下表,我需要获得在考试中获得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 |
+--------------+-------------+

不起作用。它只会计算特定学生的所有成绩。请帮我解决这个问题。谢谢。

2 个答案:

答案 0 :(得分: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

Example on SQL-Fiddle返回:

a_count   cnt
      2     3

答案 1 :(得分:1)

您可以使用子查询:

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