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?
All you need to do is use the multiplication operator (*) between the two multiplicand columns ( price * quantity ) in a simple SELECT query. You can give this result an alias with the AS keyword; in our example, we gave the multiplication column an alias of total_price .
The SQL multiply ( * ) operator is used to multiply two or more expressions or numbers.
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)))
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:
1 for >0
, 0 for 0
and -1 for <0
.% 2
against the count() of negative numbers returns either0.5-1=-0.5
=>round to -1) if there is an odd number of negative numbers0.5-0= 0.5
=>round to 1) if there is an even number of negative numbersIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With