Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL AVG returning an int

In one of my queries it appears that the AVG function is returning an int.

select ..., AVG(e.employee_level)avg_level 

How do I get it to return floating point values? I tried casting it but all my rows for avg_level were still integers.

like image 577
CodeKingPlusPlus Avatar asked Jun 19 '12 17:06

CodeKingPlusPlus


People also ask

What data type does AVG return SQL?

The SUM() and AVG() functions return a DECIMAL value for exact-value arguments (integer or DECIMAL ), and a DOUBLE value for approximate-value arguments ( FLOAT or DOUBLE ).

How do you round an average to the nearest integer in SQL?

If you are in SQL Server, just use round(avg(column * 1.0), 0) .

How do you round an average number in SQL?

SQL AVG() with ROUND(), group byThe SQL ROUND() is used to round the value up to a specific decimal places. The GROUP BY clause with aggregate function makes the result within a group.

What does AVG () do in SQL?

The AVG() function returns the average value of a numeric column.

How do you use Avg in SQL Server?

AVG () computes the average of a set of values by dividing the sum of those values by the count of nonnull values. If the sum exceeds the maximum value for the data type of the return value, AVG () will return an error. AVG is a deterministic function when used without the OVER and ORDER BY clauses.

What is the difference between cast () and AVG () in SQL?

CAST() function inside AVG() function. The SQL AVG() function returns the average value with default decimal places. The CAST() is used to increase or decrease the decimal places of a value. The CAST() function is much better at preserving the decimal places when converting decimal and numeric data types.

How to get the average value of a set in SQL?

Summary: this tutorial, we will show you how to use SQL AVG function to get the average value of a set. The SQL AVG function is an aggregate function that calculates the average value of a set. The following illustrates the syntax of the SQL AVG function:

Why does the AVG() function ignore null values?

This is because the SQL AVG () function ignores NULL s and simply calculates the average of the other records with numeric values. That is, it ignores the value from the row shown below. Imagine you have some duplicated data in your tables, and you want to ignore duplicate values when calculating the average.


2 Answers

Try to do it like this:

AVG(Cast(e.employee_level as Float)) as avg_level 

Also i found this topic where you can find some another approach but i not used its and don't know exactly whether works or not.

like image 184
Simon Dorociak Avatar answered Oct 07 '22 01:10

Simon Dorociak


Casting is more certain, but ...AVG(1.0 * e.employee_level)... might do it as well, and can be more legible.

like image 26
Philip Kelley Avatar answered Oct 07 '22 02:10

Philip Kelley