Why does SQL Server round off results of dividing two integers?

后端 未结 6 1753
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 17:22

I have a table with a smallint column that contains percentages as whole numbers (i.e., 50, 75, 85, etc.)

When I divide this column by 100, as in

SEL         


        
相关标签:
6条回答
  • 2020-12-03 17:31

    NB - Be careful in that the remainder of integer division is not rounded. Rather, it is dropped. This is equivalent to calling the FLOOR sql function.

    This is common, and is defined as such because when multiplying two integers, a fraction will never occur. Therefore a fraction-handling methodology is never assumed when multiplying integers, but the same cannot be said for integer division.

    This can often have an impact when doing dateTime arithmetic in SQL.

    0 讨论(0)
  • 2020-12-03 17:33

    When you do integer division (integer divided by integer) you always get an integer answer. 50/100 = .50, which is 0 in integer-speak.

    Have you tried dividing MY_COLUMN by 100.0?

    0 讨论(0)
  • 2020-12-03 17:33

    When you are using /(Divide) operator it

    Returns the data type of the argument with the higher precedence.

    and

    If an integer dividend is divided by an integer divisor, the result is an integer that has any fractional part of the result truncated.

    So, you need to cast at least one of the operands to appropriate type: decimal and numeric or float or real.

    0 讨论(0)
  • 2020-12-03 17:34

    You're doing integer division. 50/100 is 0 with a remainder of 50.

    You need to use floating point division.

    0 讨论(0)
  • 2020-12-03 17:49

    Cast whole numbers.

    SELECT (cast(50 AS float)/100)
    
    0 讨论(0)
  • 2020-12-03 17:50

    You're dividing 2 integers which results in another integer.

    It should possible to cast that way, too

    SELECT (50/100)::numeric;

    0 讨论(0)
提交回复
热议问题