Calculate AVERAGE from 2 columns for each row in SQL

我的梦境 提交于 2019-12-08 04:55:34

问题


As an example I will have this table from MySQL

Id  | Name  | Grade 1  | Grade 2 | Average

1.  | Jack  | 9        | 10      |
2.  | Jimmy | 9        | 8       |
2.  | Emmy  | 9        | 7       |

So, in the Average field from this table, I need to calculate the AVERAGE from the Grade 1 and Grade 2 fields. I tried a lot of possiblities which I know they are wrong like:

UPDATE table_name SET Average=AVG(Grade 1 + Grade 2)

I there a way to do this? Can anyone help me? Thanks!


回答1:


You need to add the fields together and divide by the number of fields. If your Average field is of DECIMAL type you don't really even need to specify the ROUND function. Any decimal exceeding the declaration will just be truncated (SQL Fiddle) :

UPDATE table_name 
SET AVERAGE = (grade1 + grade2) / 2;

In your example you only have two fields that you are getting the average of. So Average decimal(3,1) would work for you since the most the decimal portion will ever be is .5. So the ROUND function is clearly not needed.



来源:https://stackoverflow.com/questions/26280947/calculate-average-from-2-columns-for-each-row-in-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!