我想保护以下语句免于除零错误。我怎样才能做到这一点?
SELECT [MyColumn] = sum(
case when v.Process_FundingDt
between @begDt and @endDt
and v.Loan_Purpose_Desc = 'PURCHASE'
then v.Loan_LoanAmt
else 0
end
) / sum (
case when v.Process_FundingDt
between @begDt and @endDt
then v.Loan_LoanAmt else 0
end
)
答案 0 :(得分:2)
这可能有所帮助:
select [MyColumn] = case when Denominator = 0 then NULL else Numerator / Denominator end
from (
select sum(
case when v.Process_FundingDt between @begDt and @endDt and v.Loan_Purpose_Desc = 'PURCHASE' then v.Loan_LoanAmt
else 0 end ) as Numerator,
sum (
case when v.Process_FundingDt between @begDt and @endDt then v.Loan_LoanAmt
else 0 end ) as Denominator
) as Edgar
添加缺少的FROM
子句可能会更好。
当然,它可能会与this功能发生冲突,具体取决于查询优化器的功能。
答案 1 :(得分:0)
您可以使用此处提到的 NULLIF 方法:how to avoid divide by zero error
SELECT [MyColumn] = sum(
case when v.Process_FundingDt
between @begDt and @endDt
and v.Loan_Purpose_Desc = 'PURCHASE'
then v.Loan_LoanAmt
else 0
end
) / NULLIF(sum (
case when v.Process_FundingDt
between @begDt and @endDt
then v.Loan_LoanAmt else 0
end, 0)
)