Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

SQL AVG function does not return decimal, only unrounded integers

Posted on 2004-04-19
3
Medium Priority
?
5,345 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 1000 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 1000 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

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

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

Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
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
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

610 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