sqlsql-serveroracle-database

Multiplication aggregate operator in SQL


In SQL there are aggregation operators, like AVG, SUM, COUNT. Why doesn't it have an operator for multiplication? "MUL" or something.

I was wondering, does it exist for Oracle, MSSQL, MySQL ? If not is there a workaround that would give this behaviour?


Solution

  • By MUL do you mean progressive multiplication of values?

    Even with 100 rows of some small size (say 10s), your MUL(column) is going to overflow any data type! With such a high probability of mis/ab-use, and very limited scope for use, it does not need to be a SQL Standard. As others have shown there are mathematical ways of working it out, just as there are many many ways to do tricky calculations in SQL just using standard (and common-use) methods.

    Sample data:

    Column
    1
    2
    4
    8
    
    COUNT : 4 items (1 for each non-null)
    SUM   : 1 + 2 + 4 + 8 = 15
    AVG   : 3.75 (SUM/COUNT)
    MUL   : 1 x 2 x 4 x 8 ? ( =64 )
    

    For completeness, the Oracle, MSSQL, MySQL core implementations *

    Oracle : EXP(SUM(LN(column)))   or  POWER(N,SUM(LOG(column, N)))
    MSSQL  : EXP(SUM(LOG(column)))  or  POWER(N,SUM(LOG(column)/LOG(N)))
    MySQL  : EXP(SUM(LOG(column)))  or  POW(N,SUM(LOG(N,column)))
    


    * LOG(0) and LOG(-ve) are undefined. The below shows only how to handle this in SQL Server. Equivalents can be found for the other SQL flavours, using the same concept

    create table MUL(data int)
    insert MUL select 1 yourColumn union all
               select 2 union all
               select 4 union all
               select 8 union all
               select -2 union all
               select 0
    
    select CASE WHEN MIN(abs(data)) = 0 then 0 ELSE
           EXP(SUM(Log(abs(nullif(data,0))))) -- the base mathematics
         * round(0.5-count(nullif(sign(sign(data)+0.5),1))%2,0) -- pairs up negatives
           END
    from MUL
    

    Ingredients: