简体   繁体   English

当一组浮点值加起来为 0 时,为什么 SQL SUM() function 返回非零总数?

[英]Why does the SQL SUM() function return a non-zero total when a group float values should add up to 0?

I am facing this issue with the SQL SUM() function I have three values that have the sum equals to Zero as you can see the values but with the SUM() function the answer is that strange values as shown.我在使用 SQL SUM() function 时遇到了这个问题,我有三个总和等于 0 的值,如您所见,但是使用SUM() ZC1C425268E68385D1AB5074C1 的值很奇怪,如图所示4。

Select Qty from Stock where ProductCode = '5LINE-15-1-30RU' 
    
Output : 
    
1. 49.72
2. -31.065
3. -18.655
    
Select SUM(Qty) from Stock where ProductCode = '5LINE-15-1-30RU'
    
Output : 
    
-3.5527136788005E-15

The result have to be 0 but I got this awkward value.结果必须为 0,但我得到了这个尴尬的值。

Column Qty is a float .Qty是一个float

You are using a float datatype which stores values as approximations c.f.您正在使用float数据类型,它将值存储为近似值 c.f。

Approximate-number data types for use with floating point numeric data.用于浮点数值数据的近似数数据类型。 Floating point data is approximate;浮点数据是近似的; therefore, not all values in the data type range can be represented exactly.因此,并非数据类型范围内的所有值都可以准确表示。

For cases when you need precision, eg when you need decimal/int values you should use a decimal / int datatype.对于需要精度的情况,例如,当您需要小数/整数值时,您应该使用decimal / int数据类型。 Its pretty rare that you would use a float .你很少会使用float If you are unable to change the column datatype you can convert it before summing eg如果您无法更改列数据类型,则可以在求和之前对其进行转换,例如

declare @Test table (Qty float);

insert into @Test (Qty)
values
(49.72),
(-31.065),
(-18.655);

select sum(Qty), sum(convert(money,Qty)) from @Test;

Returns:回报:

FloatSum浮点数 ConvertedSum转换总和
-3.5527136788005E-15 -3.5527136788005E-15 0.00 0.00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM