Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I have this Tsql statement but I'm getting the above (question) error.

I wanna get the Percentage differance between Amount1 and Amount2

I learnt i have to use a CASE Statement but i ain't getting it right.

My statement:

SQL
SELECT 
[Projects],
Sum([Amount1]) AS [Total_Amount1], 
Sum([Amount2]) AS [Total_Amount2],,
Sum([Amount1]) - Sum([Amount2]) AS [DELTA],

Sum([Amount1]) - Sum([Amount2])/ Sum([Amount2]) * 100 AS [ABWEICHUNG],

Sum([Amount3]) AS [Total_Amount3],
Sum([Amount4]) AS [Total_Amount4]
FROM tbl1
GROUP BY [Projects]


Thanks
Posted
Updated 24-Feb-15 3:41am
v4

8134 is a divide by zero. You can add a case statement to check when SUM(Amount2) is 0 and handle it differently or what I have done in the past is instead something like this:

SQL
Sum([Amount2])/ (Sum([Amount2]+0.0000001))


This will always avoid the divide by zero and adding that small amount likely won't affect any results, depending on your data.
 
Share this answer
 
Comments
hypermellow 24-Feb-15 10:24am    
5+ for the '+0.0000001' work around ... will be using this one myself. :)
mikybrain1 24-Feb-15 10:34am    
@RyanDev. Its seems to be alright but I'm gonna cross check it with a calculator for the outcomes.

Thnx by the way
ZurdoDev 24-Feb-15 10:36am    
You're welcome.
Error 8134 is "divide by zero" - it would have been helpful to include that information in the question!

The error occurs because Sum(Amount2) is returning 0 for at least one group. You can avoid the error by converting 0 to NULL using the NullIf function.

You'll also need parentheses around the Sum(Amount1) - Sum(Amount2), since the division operator has higher precedence than the subtraction operator.
SQL
Sum(Amount1) - Sum(Amount2) / Sum(Amount2)
=== Sum(Amount1) - (Sum(Amount2) / Sum(Amount2))
=== Sum(Amount1) - 1


Although technically correct, putting the * 100 at the end makes the calculation more confusing to read. It's not immediately obvious whether you're multiplying the numerator or the denominator by 100. Moving the multiplication to the start would make this clearer.

Try using:
SQL
100 * (Sum([Amount1]) - Sum([Amount2])) / NullIf(Sum([Amount2]), 0) AS [ABWEICHUNG],
 
Share this answer
 
This line throws error
SQL
Sum([Amount1]) = 0 - Sum([Amount2])/ Sum([Amount2]) * 100 AS [ABWEICHUNG],

It should be..
SQL
(0 - Sum([Amount2])/ Sum([Amount2]) * 100) AS [ABWEICHUNG],
Please elaborate your question..what result exactly you need
 
Share this answer
 
Comments
mikybrain1 24-Feb-15 9:31am    
That was a tip mistake from me. Question has been edited. My Fault. The error still exist

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900