Reputation: 705
I am trying to eliminate this division by zero error using CASE
in my T-SQL SELECT
statement. For some reason, I keep getting the error. Here is my logic.
SELECT
CASE
WHEN tb1.wpf = 0.000 THEN '0.000'
ELSE SUM(tb2.weight/tb1.wpf)
END AS Average
FROM Table1 tb1, table2 tb2
GROUP BY tb1.wpf
I did not include joins and all my logic to keep my question specific to this case. How can I get rid of this error?
Upvotes: 2
Views: 4141
Reputation: 3493
The CASE
is going to be applied to the aggregate, not individual bits. Try this:
SELECT SUM(Average) FROM (
SELECT
CASE
WHEN tb1.wpf = 0 THEN 0
ELSE tb2.weight / tb1.wpf
END AS Average
FROM Table1 tb1, table2 tb2
) a
Upvotes: 3