Solved

SQL Server Divide columns and handle divide by zero

Posted on 2015-01-25
1
79 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:
Simon 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

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
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.
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Viewers will learn how the fundamental information of how to create a table.

730 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