Home >Database >Mysql Tutorial >How to Correctly Calculate the Average of Multiple Columns in SQL?

How to Correctly Calculate the Average of Multiple Columns in SQL?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 10:01:14165browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn