Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert AVG() function to decimal in SQL SERVER

Help! I have a table looks like the following one.

SELECT *
FROM tblshipline 
WHERE MethodShipped = 'FEDEX'

Then I get

Qtyshipped
2
3
15
3
10
9
10

Now the question is to calculate the AVERAGE of qtyshipped and round it to 2 decimal number.

My Code is

SELECT CONVERT(decimal(8,6), ROUND(AVG(Qtyshipped),2))  
FROM TblShipLine
WHERE MethodShipped= 'FEDEX'

The Answer should be 7.430000 , But it always returns 7.000000. I appreciate any advice, thanks!

like image 362
Stanley Avatar asked Mar 11 '17 22:03

Stanley


1 Answers

Here we take your INT value and add 0.0 which is a fast conversion to float. Then we apply the round() and convert()

Declare @YourTable table (Qtyshipped int)
Insert into @YourTable values
(2),
(3),
(15),
(3),
(10),
(9),
(10)

Select convert(decimal(8,6),round(Avg(Qtyshipped+0.0),2))
 From  @YourTable

Returns

7.430000
like image 109
John Cappelletti Avatar answered Sep 30 '22 01:09

John Cappelletti