简体   繁体   English

SQL ROUND AVG

[英]SQL ROUND A AVG

I have that 2 tables: 我有2个表:

Evaluation
id_student  teste
----------- -----
1           16
1           10
1           20
1           13

Student
id          name
----------- ------
1           Jonh

And I want do the average of the column "teste" for the student with the id 1. I used that query: 我想为id为1的学生做“teste”列的平均值。我使用了该查询:

select ROUND(AVG(e.teste),0) from Student s, Evaluation e
where s.id=e.id_student and s.id=1 group by s.nome

That query return the value 14, but if i go to the calculator and do (16+10+20+13) / 4 it gives me 14.75 I already tryed with the ROUND to round the number, the query should return 15 instaed of 14. Somebody know how I can soulve this? 该查询返回值14,但如果我去计算器并做(16 + 10 + 20 + 13)/ 4它给了我14.75我已经尝试使用ROUND来舍入数字,查询应返回15 instaed of 14有人知道我怎么能忍受这个? Thanks and sorry my english. 谢谢,对不起我的英语。

The problem is probably that the average is calculated using integer arithmetic. 问题可能是使用整数运算来计算平均值。 You don't specify your database, but some do use integer arithmetic. 您没有指定数据库,但有些确实使用整数运算。 This has nothing to do with the round() . 这与round()无关。

Try this out: 试试这个:

select AVG(e.teste)
from Student s join
     Evaluation e
     on s.id = e.id_student 
where s.id = 1;

Notice the changes: 注意这些变化:

  • Fixed the join use proper, explicit join syntax. 修复了join使用正确的显式join语法。
  • Removed the round() . 删除了round()
  • Removed the group by because you only seem to want to return one row. 删除了group by因为您似乎只想返回一行。

This will return 14 and not 15 , because the calculation is integer 59 divided by integer 4 to return an integer -- so it is truncated not rounded. 这将返回14而不是15 ,因为计算是整数59除以整数4以返回整数 - 因此它被截断而不是舍入。 You can fix this by converting to some sort of decimal/float representation. 您可以通过转换为某种十进制/浮点表示来解决此问题。 Often the easiest way is just by multiplying by 1.0: 通常最简单的方法是乘以1.0:

select AVG(e.teste * 1.0)
from Student s join
     Evaluation e
     on s.id = e.id_student 
where s.id = 1;

Once you have the average calculating correctly, you can apply round() if you like. 正确计算平均值后,如果愿意,可以应用round()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM