假设我有下表:
+-----------+------------+-------+
| quiz_type | student_id | score |
+-----------+------------+-------+
| class | NULL | 10 |
+-----------+------------+-------+
| class | NULL | 9 |
+-----------+------------+-------+
| student | A | 5 |
+-----------+------------+-------+
| student | B | 7 |
+-----------+------------+-------+
| student | A | 6 |
+-----------+------------+-------+
我想获得每个学生的分数总和,但需要包括每个学生的类(class)分数。换句话说,我想要一个如下的结果表:
+------------+-------+
| student_id | score |
+------------+-------+
| A | 30 |
+------------+-------+
| B | 26 |
+------------+-------+
实际上,quiz_type 列并不存在。我需要执行 GROUP BY Student_id
,但在每个组中包含 NULL
值。我已经为此苦苦挣扎了很长一段时间。有什么好的解决办法吗?
最佳答案
你可以试试这个:
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`
关于mysql - 如何使用具有默认值的分组依据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38448190/