What is wrong with this SQL Server query division calculation?

前端 未结 4 1741
梦谈多话
梦谈多话 2020-12-11 23:41

I have this table structure on a SQL Server 2008 R2 database:

  CREATE TABLE FormTest
(   
clientid char(10),
DateSelected date,
A int,
B int,
C int
)


        
相关标签:
4条回答
  • 2020-12-12 00:03

    It's because you are doing integer division. You should convert one of the operands to float, or decimal (depending on the precision and purpose of the calculation you are doing), using something like:

    ((CAST((a+ b + c) AS FLOAT) / 3) / 216647 * 10)
    

    or possibly:

    (((a+ b + c) / 3.0) / 216647.0 * 10)
    
    0 讨论(0)
  • 2020-12-12 00:05
    declare @a int
    declare @b int
    declare @c int
    set @a=65150
    set @b=4921
    set @c=1
    
    select convert(float,((@a+@b+@c)/ 216647.0 * 10) )
    
    0 讨论(0)
  • 2020-12-12 00:18

    You're performing integer arithmetic, so your results will always be rounded down to the nearest whole number. Since you're dividing by 3, then by 216647, based on the numeric inputs your result is getting rounded down to 0 every time. You'll need to use either a decimal (exact) or floating point (approximate) data type and/or casting if you want to get non-integer results.

    0 讨论(0)
  • 2020-12-12 00:27

    Dividing integers will result in an integer (The remainder part will be ignored). Hence, when dividing, work with decimals or floats. This should work in addition to the float solutions given earlier. Replace (12,2) with your preferred precision:

    SELECT clientid, (((
    Cast(a as decimal(12,2)) + 
    Cast(b as decimal(12,2)) + 
    Cast(c as decimal(12,2)) 
    ) / 3) / 216647 * 10) AS Formula1 
    FROM FormTest
    
    0 讨论(0)
提交回复
热议问题