Solved

SQL AVG function does not return decimal, only unrounded integers

Posted on 2004-04-19
3
5,332 Views
Last Modified: 2012-06-27
Dear Experts,

I am sure this is a pretty stupid question. Anyway, the following query

Select AVG(FIELDNAME) As AVGFIELDNAME ... only returns integers. What do I do to return  a decimal?

Thanks.
0
Comment
Question by:metalaureate
  • 2
3 Comments
 
LVL 8

Expert Comment

by:Dishan Fernando
ID: 10866012
create table #t
(
t decimal(5,3)
)

insert into #t values(3.4)
insert into #t values(4.5)

select * from #t

select avg(t) from #t
----------------------------------
3.950000

(1 row(s) affected)
0
 
LVL 2

Accepted Solution

by:
somchaiu earned 250 total points
ID: 10866145
The problem of AVG() function is if the input is "int" the result value is "int" too. You have to convert input to decimal to receive decimal result. for example:

1. SELECT AVG(FIELDNAME+0.0) AS AVGFIELDNAME

2. SELECT AVG(CAST(FIELDNAME AS decimal)) AS AVGFIELDNAME
0
 
LVL 8

Assisted Solution

by:Dishan Fernando
Dishan Fernando earned 250 total points
ID: 10866176
Yes .. if your column is int you must cast or convert to decimal

select avg(CAST(ColumnName AS decimal(5,2))) from TableName
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Via a live example, show how to shrink a transaction log file down to a reasonable size.

861 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question