Dividing 2 numbers in Sql Server

前端 未结 4 1046
一向
一向 2021-01-06 03:11

I am doing SQL Server query calculations and the division always gives me zero.

SUM(sl.LINES_ORDERED) 
, SUM(sl.LINES_CONFIRMED)
, SUM(sl.LINES_CONFIRMED) /          


        
相关标签:
4条回答
  • 2021-01-06 03:33

    The two problems are that you

    1. perform an integer division (SUM returns an integer), and
    2. you swapped the dividend and the divisor (that's why you get zero instead of one).

    This is how you could fix it (note that LINES_ORDERED and LINES_CONFIRMED are swapped):

    SUM(sl.LINES_ORDERED) 
    , SUM(sl.LINES_CONFIRMED)
    , (1.0*SUM(sl.LINES_ORDERED)) / SUM(sl.LINES_CONFIRMED) AS 'Percent'
    
    0 讨论(0)
  • 2021-01-06 03:37

    try

    SUM(sl.LINES_CONFIRMED) * 1.0 / SUM(sl.LINES_ORDERED)
    

    An integer devision can only return full numbers and not floating point numbers. You can force a floating point division like in the example above.

    0 讨论(0)
  • 2021-01-06 03:43

    Try it like this:

    SUM(sl.LINES_ORDERED) 
    , SUM(sl.LINES_CONFIRMED)
    , SUM(sl.LINES_CONFIRMED)*1.0 / SUM(sl.LINES_ORDERED)
    
    0 讨论(0)
  • 2021-01-06 03:52

    It will be because you're divinding two integers.

    Convert the two values in the division to decimals first:

    , SUM(convert(decimal(12,2),sl.LINES_CONFIRMED)) 
    / SUM(convert(decimal(12,2),sl.LINES_ORDERED)) AS 'Percent'
    
    0 讨论(0)
提交回复
热议问题