How to multiply numbers in a column in MySQL
lists.mysql.com
lists.mysql.com
inside mysql, i used it all the time.
for example, perhaps i want to get a sense of the distribution of users; i have a table "users" with columns "user" and "count"
i could get a log-scaled histogram like so:
select pow(int(log(count)/log(10)),10) as bin, count(*) as ct from users
this would get a table like such (forgive my ascii art)
bin | ct
----+---
1 | 12
10 | 27
100 | 35
another thing you can do is us the order of magnitude with repeat(char, num) to make a sort of visual bar chart.that said, i'm sorta glad i don't have to use mysql professionally anymore.
After much searching I came to this little nugget:
"exp(sum(log(coalesce(the field you want to multiply,1)))
The coalesce() function is there to guard against trying to calculate the logarithm of a null value and may be optional depending on your circumstances."
MySQL is full of hacks.
Remember that floating point isn't the same as the math you were taught in high school.
Horses for courses. Do the query in whatever programming language, then just multiply the numbers together. I don't try to do left outer joins on my HP12-C calculator either.
Also, consider the following case: UPDATE huge_table SET someval = (SELECT PRODUCT(x) ...). Splitting this into 50 million queries wouldn't be a very good solution.
I'm pretty sure PostgreSQL lets you extend it however you want as well.
http://dev.mysql.com/doc/refman/5.1/en/plugin-creating.html
Please do not make things up and claim your imagination as truth.
CREATE OR REPLACE FUNCTION product_sfunc(state NUMERIC, value NUMERIC)
RETURNS NUMERIC AS $$
BEGIN
IF value IS NOT NULL THEN
IF state IS NULL THEN
RETURN value;
ELSE
RETURN state * value;
END IF;
END IF;
RETURN state;
END; $$ LANGUAGE plpgsql;
CREATE AGGREGATE PRODUCT (NUMERIC) (
SFUNC = product_sfunc,
STYPE = NUMERIC
);
This took only a couple of minutes to write and didn't require any extra tools. Now I can use the PRODUCT() aggregate in queries, like this: SELECT SUM(n), PRODUCT(n) from generate_series(1, 5) as n;
sum | product
-----+---------
15 | 120
In Postgres 8.4 it also works as a windowing function which means I can use it to get a running product (is that the correct expression?): SELECT n, PRODUCT(n) OVER (ORDER BY n) from generate_series(1, 5) as n;
n | product
---+---------
1 | 1
2 | 2
3 | 6
4 | 24
5 | 120All these database engines are pretty weak. I prefer to use SAS for this kind of thing (including seeing stuff from previous/future rows.) It may not be client/server, but it is astoundingly fast for large datasets nonetheless.
Also, it seems C/C++ support is deprecated in MSSQL, so it's not a proper solution either. CLR integration is what they're pushing now.
For the product
(reduce #'* (select 'value :from 'product :flatp t))
If you want the sum change #'* to #'+.