I’m doing an insert, and one of the values I’m inserting is calculated as follows:
SUM(Value1)/(
CASE SUM(
CASE Value2 > 0
THEN 1
ELSE 0
END
) = 0
THEN 1
ELSE SUM(
CASE Value2 > 0
THEN 1
ELSE 0
END
)
)
The inner CASE-part is duplicated twice, it would be nice to set an alias or variable to this value and use that alias or variable instead.
CTE answer…
SubQuery version…
Or, more specific to the SQL you posted, but not an answer to the generic case…
(Returning NULL where you return 0 allows COALESCE to replace NULLs with 1s.)