Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

SQL Server Divide columns and handle divide by zero

Posted on 2015-01-25
1
Medium Priority
?
93 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 18

Accepted Solution

by:
Simon earned 2000 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

Fill in the form and get your FREE NFR key NOW!

Veeam® is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

Question has a verified solution.

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

Windocks is an independent port of Docker's open source to Windows.   This article introduces the use of SQL Server in containers, with integrated support of SQL Server database cloning.
When trying to connect from SSMS v17.x to a SQL Server Integration Services 2016 instance or previous version, you get the error “Connecting to the Integration Services service on the computer failed with the following error: 'The specified service …
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

636 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