6

ゼロ除算に問題があります。分母がゼロの場合、値をゼロにしたいと思います。を使用しようとするnullifと、計算値が 0 または 1 になります。

SQLは次のとおりです。

Select 
    StateCode, Month1Date,(Sum(Order)/Sum(Value)) as myValue    
from tblOrders    
     inner join tblStates on OrderStateCode = StateCode    
group by StateCode, Month1Date
4

3 に答える 3

7
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

A 0 denominator is changed to NULL, which will cause the result to be NULL. The whole result then has ISNULL() to turn any NULLs to 0's.

Personally I would not include the ISNULL() and leave the result as NULL. But it depends on use-case really.

EDIT: Deleted the CASE WHEN version as another answer had it just before mine.

于 2012-06-28T13:52:49.420 に答える
5

You need a case statement:

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
于 2012-06-28T13:52:41.730 に答える
0

これを試して。

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
于 2012-06-28T14:11:33.930 に答える