is there a PRODUCT function like there is a SUM function in Oracle SQL?

后端 未结 6 1796
别跟我提以往
别跟我提以往 2020-12-03 04:15

I have a coworker looking for this, and I don\'t recall ever running into anything like that.

Is there a reasonable technique that would let you simulate it?

6条回答
  •  自闭症患者
    2020-12-03 04:30

    Here's another way to do it. This is definitely the longer way to do it but it was part of a fun project.

    You've got to reach back to school for this one, lol. They key to remember here is that LOG is the inverse of Exponent.

    LOG10(X*Y) = LOG10(X) + LOG10(Y)

    or

    ln(X*Y) = ln(X) + ln(Y) (ln = natural log, or simply Log base 10)

    Example
    If X=5 and Y=6

    X * Y = 30

    ln(5) + ln(6) = 3.4

    ln(30) = 3.4

    e^3.4 = 30, so does 5 x 6

    EXP(3.4) = 30

    So above, if 5 and 6 each occupied a row in the table, we take the natural log of each value, sum up the rows, then take the exponent of the sum to get 30.

    Below is the code in a SQL statement for SQL Server. Some editing is likely required to make it run on Oracle. Hopefully it's not a big difference but I suspect at least the CASE statement isn't the same on Oracle. You'll notice some extra stuff in there to test if the sign of the row is negative.

    CREATE TABLE DUAL (VAL INT NOT NULL)
    INSERT DUAL VALUES (3)
    INSERT DUAL VALUES (5)
    INSERT DUAL VALUES (2)
    
        SELECT 
               CASE SUM(CASE WHEN SIGN(VAL) = -1 THEN 1 ELSE 0 END) % 2 
                   WHEN 1 THEN -1 
                   ELSE 1 
               END
             * CASE 
                    WHEN SUM(VAL) = 0           THEN 0 
                    WHEN SUM(VAL) IS NOT NULL   THEN EXP(SUM(LOG(ABS(CASE WHEN SIGN(VAL) <> 0 THEN VAL END)))) 
                    ELSE NULL 
               END
             * CASE MIN(ABS(VAL)) WHEN 0 THEN 0 ELSE 1 END
            AS PRODUCT 
          FROM DUAL
    

提交回复
热议问题