I have a query that looks like this, and which is getting a percentage:
SELECT SUM(convert(decimal(3,2),
CASE WHEN Status_ID = 1 AND State_ID = 14 THEN 1 ELSE 0 END))/
SUM(convert(decimal(3,2),CASE WHEN State_ID = 14 THEN 1 ELSE 0 END)) * 100
FROM SomeTable
This may return something like 59.77803 in a normal case. But it turns that there are (rightly) cases when the second SUM — the denominator — could be 0. Does anyone know of a way to account for this case and avoid a divide by 0 exception?
I’m using SQL Server 2005. Thanks.
I would probably use a NULL to represent uncalculatable, but it depends upon your intent in your problem domain (code expanded to show what’s going on):
The result when there are no rows in the table so the denominator would be zero – gets converted to NULL so the whole expression ends up NULL.
That code can also be simplified a little (probably because it’s already a simplified toy problem):
As an example of combining a number of different things into one query: