如何使用默认值分组?

时间:2016-07-19 01:23:24

标签: mysql

假设我有下表:

+-----------+------------+-------+
| quiz_type | student_id | score |
+-----------+------------+-------+
| class     | NULL       | 10    |
+-----------+------------+-------+
| class     | NULL       | 9     |
+-----------+------------+-------+
| student   | A          | 5     |
+-----------+------------+-------+
| student   | B          | 7     |
+-----------+------------+-------+
| student   | A          | 6     |
+-----------+------------+-------+

我想得到每个学生的分数总和,但需要包括每个学生的课程分数。换句话说,我想要一个结果表,如:

+------------+-------+
| student_id | score |
+------------+-------+
| A          | 30    |
+------------+-------+
| B          | 26    |
+------------+-------+

实际上,quiz_type列不存在。我需要执行GROUP BY student_id,但每个组都包含NULL值。我一直在努力解决这个问题。有一个很好的解决方案吗?

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

select 
    student_id,
    sum(score) + (select sum(score) from yourtable where student_id is null) as score
from yourtable
where student_id is not null
group by `student_id`

SQLFiddle Demo