我想写这个查询(所有字段都是int):
select SUM(Service.discount+((Service.price*Factor.discount)/(Factor.amount-Factor.discount)))
但有时我会收到此错误:
将表达式转换为数据类型int的算术溢出错误。
其他时候我收到此错误:
遇到零错误。
如何重写此查询以避免这些错误?
//我使用此但是溢出
select case when(Factor.amount-Factor.discount)<>0 then
Service.discount+((Service.price*Factor.discount)/(Factor.amount-Factor.discount))
else
Service.discount
end
from Factor inner join Service on Factor.code=Service.factorCode
答案 0 :(得分:1)
算术溢出:根本不使用sum,取下SUM并从任一端取下括号。 除以零:看看Jonny的回答(我认为他的意思是当factor.amount-factor.discount为零时你想做什么......)
所以也许:
select case when discount2 <> 0 then discount+((price*discount)/(discount2)) else
discount+(price*discount) end FROM SERVICE
答案 1 :(得分:0)
select
CASE (Factor.amount-Factor.discount)
WHEN 0
-- choose the result when Factor.amount-Factor.discount = 0 and replace this line
ELSE
SUM(Service.discount+((Service.price*Factor.discount)/
(Factor.amount-Factor.discount)))
END
...
答案 2 :(得分:0)
SELECT CASE
WHEN (Factor.amount-Factor.discount) <> 0
THEN
CONVERT(FLOAT,Service.discount+((Service.price*Factor.discount)/(Factor.amount-
Factor.discount)))
ELSE
Service.discount
END
FROM Factor INNER JOIN Service ON Factor.code=Service.factorCode
最好确定要查看的小数位数:
CONVERT(decimal(10,2),Service.discount+((Service.price*Factor.discount)/(Factor.amount-Factor.discount)))