Skip to content
Advertisement

Why is my calculating a percentage not working correctly when I am dividing?

I am trying to see what percentage of customers paying LL and the percentage of customers that are paying LP. For example I have 1 customer in LL and 1 in LP so percentage should be 50% in Cust_LL_Pct and Cust_LP_Pct. I have tried using a ISNULL, and set it as 0, but that didn’t fix the problem. The Pct Columns are giving be only 0 and 1, nothing in between. enter image description here

Advertisement

Answer

The problem is integer division. When both operands are integers, SQL Server produces an integer result: for example, 3/2 yields 1, not 1.5.

You need to force decimal context for the operation, for example by multiplying with a (dummy) decimal value, like:

I would not recommend using isnull(..., 0) for the right operand of a division: if the value is actually null, you get a division by 0, which is a fatal error. On the other hand, dividing by null yields null, which does not fail, and seems more relevant.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement