为什么将AVG(整数列)转换为DECIMAL至少返回六位小数?

时间:2010-10-15 14:39:24

标签: sql sql-server sql-server-2008

考虑这个问题:

WITH Scores (score)
     AS
     (
      SELECT CAST(score AS INTEGER)
        FROM (
              VALUES (0), 
                     (10), 
                     (10)
             ) AS Scores (score)
     )
SELECT AVG(CAST(score AS DECIMAL(19, 8))) AS precision_eight, 
       AVG(CAST(score AS DECIMAL(19, 7))) AS precision_seven, 
       AVG(CAST(score AS DECIMAL(19, 6))) AS precision_six, 
       AVG(CAST(score AS DECIMAL(19, 5))) AS precision_five, 
       AVG(CAST(score AS DECIMAL(19, 4))) AS precision_four
  FROM Scores;

结果:

precision_eight | precision_seven | precision_six | precision_five | precision_four 
     6.66666666 |       6.6666666 |      6.666666 |       6.666666 |       6.666666 

为什么我总是得到至少六位小数?这是记录在案的行为?

(我正在运行SQL Server 2008)

2 个答案:

答案 0 :(得分:9)

小数的AVG始终返回“十进制(38,s)除以十进制(10,0)”数据类型(see here

您必须将AVG结果转换为所需的精度。

答案 1 :(得分:2)

我准备发布与Jappie's answer类似的内容以及此示例,以说明幕后发生的事情。

declare @a int
set @a = 0
declare @b int
set @b = 10
declare @c int
set @c = 10

declare @n decimal(10,0)
set @n = 3

select cast((@a+@b+@c) as decimal(38,4))/@n