我在除以零时遇到问题。如果分母为零,我希望该值为零。当我尝试使用nullif
时,我最终得到一个零或一作为计算值。
这是SQL:
Select
StateCode, Month1Date,(Sum(Order)/Sum(Value)) as myValue
from tblOrders
inner join tblStates on OrderStateCode = StateCode
group by StateCode, Month1Date
我在除以零时遇到问题。如果分母为零,我希望该值为零。当我尝试使用nullif
时,我最终得到一个零或一作为计算值。
这是SQL:
Select
StateCode, Month1Date,(Sum(Order)/Sum(Value)) as myValue
from tblOrders
inner join tblStates on OrderStateCode = StateCode
group by StateCode, Month1Date
Select
StateCode,
Month1Date,
ISNULL(Sum(Order) / NULLIF(Sum(Value), 0), 0) AS myValue
from
tblOrders
inner join
tblStates
on OrderStateCode = StateCode
group by
StateCode,
Month1Date
0
分母更改为NULL
,这将导致result
为NULL
。然后整个结果必须ISNULL()
将任何 NULL 变为 0。
就我个人而言,我不会包含ISNULL()
并将结果保留为NULL
. 但这实际上取决于用例。
编辑:删除了 CASE WHEN 版本,因为另一个答案就在我之前。
你需要一个案例陈述:
Select StateCode, Month1Date,
(case when sum(value) = 0 then 0 else Sum(Order)/Sum(Value)
end) as myValue
from tblOrders inner join
tblStates
on OrderStateCode = StateCode
group by StateCode, Month1Date
试试这个。
SELECT StateCode, Month1Date,
CASE WHEN SUM(Value) <> 0 THEN(SUM(Order)/SUM(Value))
ELSE 0 END as myValue
FROM tblOrders
INNER JOIN tblStates ON OrderStateCode = StateCode
GROUP BY StateCode, Month1Date