Solved

SQL Server Divide columns and handle divide by zero

Posted on 2015-01-25
1
75 Views
Last Modified: 2015-01-25
In SQL Server (2012), I want to divide the values of 2 columns. There are cases where there will be division by zero. I want to do the calculation and handle the division by zero gracefully. A simple example is AB / Hits to get Average. Some AB fields will be zero. Some sort of If statement? If AB = 0, then Average = ".000", else AB/Hits? Thanks for any help.
0
Comment
Question by:dodgerfan
1 Comment
 
LVL 18

Accepted Solution

by:
SimonAdept earned 500 total points
ID: 40569305
Two choices:
1. Use a where clause to exclude the rows with zero denominators.
2. Use a case statement to set the zero denominators to null.

Both demonstrated below...
declare @t1 table (id int,num1 int,num2 int)

insert into @t1
select 1,1,1 union all
select 2,3,2 union all
select 3,0,1 union all
select 4,1,0  union all
select 5,1,null union all
select 6,null,6 

select id,num1,num2,num1/num2 as IntegerDivision,(0.0+num1)/num2 as DecimalDivision 
from @t1 where num2<>0

select id,num1,num2
,cast(num1 as decimal)/case when num2=0 then null else num2 end as DecimalDivision
from @t1

Open in new window

0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now