devxlogo

Calculating the Average of a Column

Calculating the Average of a Column

Question:
I’m doing a Web front for a database that contains data about temperature. How do I calculate an average temperature using SQL code?

Answer:
Use the AVG function to get an average of all the values in a single column. With a table called TestTable and this data:

Temperature          -------------------- 656532788056

This query will return an average of all the rows:

SELECT AVG(Temperature) AS AvgTempFROM TestTableAvgTemp                                  ---------------------------------------- 62.666666

In this case, the Temperature column is of data type decimal. If, for some reason, your Temperature column was data type int and you want the same results, use the CAST function like this:

SELECT AVG(CAST(Temperature AS decimal))FROM TestTable

devx-admin

Share the Post: