我有一张这样的表:
mysql> select * from studentscore;
+------------+-----------+-------+
| student_id | cource_id | score |
+------------+-----------+-------+
| 1 | 1 | 80 |
| 1 | 2 | 90 |
| 1 | 3 | 85 |
| 1 | 4 | 78 |
| 2 | 2 | 53 |
| 2 | 3 | 77 |
| 2 | 5 | 80 |
| 3 | 1 | 71 |
| 3 | 2 | 70 |
| 3 | 4 | 80 |
| 3 | 5 | 65 |
| 3 | 6 | 75 |
| 4 | 2 | 90 |
| 4 | 3 | 80 |
| 4 | 4 | 70 |
| 4 | 6 | 95 |
| 5 | 1 | 60 |
| 5 | 2 | 70 |
| 5 | 5 | 80 |
| 5 | 6 | 69 |
| 6 | 1 | 76 |
| 6 | 2 | 88 |
| 6 | 3 | 87 |
| 7 | 4 | 80 |
| 8 | 2 | 71 |
| 8 | 3 | 58 |
| 8 | 5 | 68 |
| 9 | 2 | 88 |
| 10 | 1 | 77 |
| 10 | 2 | 76 |
| 10 | 3 | 80 |
| 10 | 4 | 85 |
| 10 | 5 | 83 |
| 11 | 3 | 80 |
| 12 | 4 | 99 |
| 13 | 5 | 74 |
+------------+-----------+-------+
我想显示student_id和学生的平均分数高于80.
我想要的输出是这样的:
+------------+-------------------+
| student_id | Average |
+------------+-------------------+
| 1 | 83.25 |
| 4 | 83.75 |
| 6 | 83.66666666666667 | // and how can I make this result shorter like 83.67?
| 7 | 80 |
| 9 | 88 |
| 10 | 80.2 |
| 11 | 80 |
| 12 | 99 |
+------------+-------------------+
我尝试过以下代码
mysql> select student_id, avg(score) as average_score
-> from studentscore
-> group by student_id
-> where avg(score) >= 80;
它给了我一个语法错误。
我通过规则知道where子句应该在group by子句之前,但我不能,因为where子句取决于group by子句的结果,如果我切换它们的位置,它会给我另一个错误(“无效使用组功能“)。
有人可以告诉我如何获得我想要的桌子吗?
答案 0 :(得分:3)
使用“having”而不是“where”
答案 1 :(得分:1)
使用having
代替where
。
这是区别:
在您的情况下,第二个是唯一可行的解决方案。
答案 2 :(得分:0)
select student_id, avg(score) as average_score
from studentscore
group by student_id
having avg(score) >= 80;
答案 3 :(得分:0)
where
会对您的数据应用过滤器,而having
会应用过滤后分组。 round(,2)
将按照您的要求进行格式化:
select student_id, round(avg(score), 2) as average_score
from studentscore
group by student_id
having average_score >= 80;