Home >Database >Mysql Tutorial >How to Correctly Calculate the Average of Multiple Columns in SQL?
Error in Calculating Average of Multiple Columns
In an attempt to determine the average of multiple columns in a table named 'Request,' a SQL query was employed:
Select Req_ID, Avg(R1+R2+R3+R4+R5) as Average from Request Group by Req_ID
However, instead of producing the intended average, the query returned the sum of the values. To correct this error, the query can be modified to the following:
SELECT *, (SELECT AVG(c) FROM (VALUES(R1), (R2), (R3), (R4), (R5)) T (c)) AS [Average] FROM Request
This revised query utilizes subqueries and the AVG aggregate function to correctly calculate the average for each row in the 'Request' table.
The above is the detailed content of How to Correctly Calculate the Average of Multiple Columns in SQL?. For more information, please follow other related articles on the PHP Chinese website!