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
Release: 2024-12-25 10:01:14
Original
202 people have browsed it

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
Copy after login

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 
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template