Find the average of two combined columns in sql

≡放荡痞女 提交于 2019-11-29 10:42:05

By definition, AVG(col1) = SUM(col1)/COUNT(*) and AVG(col2) = SUM(col2)/COUNT(*), therefore (SUM(col1)+SUM(col2))/COUNT(*) = AVG(col1) + AVG(col2).

Also, the commutativity of addition gives us (SUM(col1)+SUM(col2))/COUNT(*) = SUM(col1+col2)/COUNT(*) and hence AVG(col1+col2).

To use the avg function,

SELECT avg(col1 + col2)
FROM test
WHERE uid=5;

SQLFIDDLE DEMO

Is this what you are looking for?

SELECT avg(col1 + col2)
FROM test
where uid = 5
group by uid

SELECT avg(col1 + col2) as avgtotal

FROM test WHERE uid=5

i got my answer here , so i will add this note which may help others:

1.avg(col1+col2) as avg_col1_plus_col2,
2.avg(col1) + avg(col2) as avg_col1_plus_avg_col2,
3.avg(col1+col2)/2 as avgTotal1, 
4.avg(col1)/2+avg(col1)/2 as avgTotal2

sentence 1 is equal to sentence 2 as eggyal explained,grammar is ok but logically its not the result that we want, so we need to divide the average by columns numbers as in sentence 3 and 4.

SELECT ((SUM(col1) + SUM(col2)) / (COUNT(col1) + COUNT(col2))) as a
FROM test
WHERE uid=5;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!