Solved

SQL Server AVG Function Data Type Restriction

Posted on 2011-09-22
2
292 Views
Last Modified: 2012-05-12
Hello Experts -
I have a SQL Server 2008 R2 table with a column of type SMALLINT on which I would like to calculate (and drop into a different table) a variety of averages (presumably using the AVG function).  The calculated averages won't always be integers so I'm expecting to use a NUMERIC(6, 2) data type for the results in the second table.  If I am reading the data typing detail for the AVG function correctly, it sounds like I can't use the SMALLINT data type on the source field if I want the calculated value to be NUMERIC.  This strikes me as absurd - it's easy to envision many scenarios where you'd start with SMALLINTs and then calculate results that are NUMERIC.  Such a rule would force a re-typing requirement that simply seems unnecessary.  Two questions:

1.  Is my understanding of the data typing for the source field called by the AVG function correct?
2.  If so, are there any straightforward workarounds that will not require me to re-type my source field from INT to NUMERIC, even though that field only holds INT values?

Thanks all.

-- Rick
0
Comment
Question by:MinnRick
2 Comments
 
LVL 5

Accepted Solution

by:
Eduardo Goicovich earned 500 total points
ID: 36584174
use convert function to meet your needs

example

INSERT INTO tablex (fieldNumeric(6,2))
SELECT
AVG(
CONVERT(decimal(18,4),smallintSourceField))
FROM tabley
0
 

Author Closing Comment

by:MinnRick
ID: 36584372
Yes, works perfectly.  Thanks very much belfegor.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

After restoring a Microsoft SQL Server database (.bak) from backup or attaching .mdf file, you may run into "Error '15023' User or role already exists in the current database" when you use the "User Mapping" SQL Management Studio functionality to al…
SQL Server engine let you use a Windows account or a SQL Server account to connect to a SQL Server instance. This can be configured immediatly during the SQL Server installation or after in the Server Authentication section in the Server properties …
This video discusses moving either the default database or any database to a new volume.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

758 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now