Solved

SQL AVG function does not return decimal, only unrounded integers

Posted on 2004-04-19
3
5,337 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

707 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