0

The following is part of a SELECT clause that is giving me divide by 0 error:

(SUM([Hours])/(SUM(CASE WHEN J.Description <> 'I' THEN 1 ELSE 0 END))

The following is how I am rectifying the denominator for the divide by 0 error:

CASE WHEN(SUM(CASE WHEN J.Description <> 'I' THEN 1 ELSE 0 END)) = 0 THEN 1 ELSE SUM(CASE WHEN J.Description <> 'I' THEN 1 ELSE 0 END))  AS 'MTBUR'

This is leaving me syntactical errors. What am I doing wrong?

So basically if the SUM = 0 then I want the denominator to be 1 ELSE

SUM(CASE WHEN J.Description <> 'I' THEN 1 ELSE 0 END
J.S. Orris
  • 4,653
  • 12
  • 49
  • 89

2 Answers2

1

How about this? Let the else portion of your case expression be NULL so the sum will be NULL if there are no rows where Description = 'I'

SUM([Hours]) /  ISNULL(SUM(CASE WHEN J.Description <> 'I' THEN 1 END), 1)
Sean Lange
  • 33,028
  • 3
  • 25
  • 40
1

CASE WHEN(SUM(CASE WHEN J.Description <> 'I' THEN 1 ELSE 0 END)) = 0 THEN 1 ELSE SUM (CASE WHEN J.Description <> 'I' THEN 1 ELSE 0 END)) END AS 'MTBUR'

Needed another END to end nested case

J.S. Orris
  • 4,653
  • 12
  • 49
  • 89