Get rows product (multiplication)

后端 未结 3 705
清歌不尽
清歌不尽 2020-12-19 02:07

SO,

The problem

I have an issue with rows multiplication. In SQL, there is a SUM() function which calculates sum for some field

3条回答
  •  忘掉有多难
    2020-12-19 03:02

    If you need this type of calculations often, I suggest you store the signs and the logarithms in separate columns.

    The signs can be stored as 1 (for positives), -1 (for negatives) and 0 (for zero.)

    The logarithm can be assigned for zero as 0 (or any other value) but it should not be used in calculations.

    Then the calculation would be:

    SELECT 
        CASE WHEN EXISTS (SELECT 1 FROM test WHERE  AND datasign = 0)
             THEN 0
             ELSE (SELECT 1-2*(SUM(datasign=-1)%2) FROM test WHERE )
        END AS resultsign,
    
        CASE WHEN EXISTS (SELECT 1 FROM test WHERE  AND datasign = 0)
             THEN -1            -- undefined log for result 0
             ELSE (SELECT SUM(datalog) FROM test WHERE  AND datasign <> 0)
        END AS resultlog
      ;
    

    This way, you have no overflow problems. You can check the resultlog if it exceeds some limits or just try to calculate resultdata = resultsign * EXP(resultlog) and see if an error is thrown.

提交回复
热议问题