Dividing 2 numbers returns 0

后端 未结 3 445
一向
一向 2021-01-28 06:48

I\'m trying to divide 2 counts in order to return a percentage.

The following query is returning 0:

select (
    (select COUNT(*) from sax         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-28 07:29

    The issue is caused because you are dividing 2 int values, which by default will output an int as it takes the data types used in the calculation to determine the data type of the output, so effectively if you do this:

    select 50/100 as result
    

    You get 0.5 output as 0 as it rounds it to an int (no decimal places).

    If you however specify decimals:

    select 50.0/100.0 as result
    

    You would get 0.5 as a decimal, which you could multiply by 100 to get 50%.

    So updating your syntax to multiply by 1.0 and making the counts into decimals would give you the correct result:

    select (
    (select COUNT(*) from saxref..AuthCycle where endOfUse is null and addDate >= '1/1/2014')*1.0 / 
    (select COUNT(*) from saxref..AuthCycle where addDate >= '1/1/2014')*1.0
    ) as Percentage
    

提交回复
热议问题