Thursday, April 8, 2010

How to get product of column values using simple select.

This is a simple problem which states that you need to write a simple select query that will give the product of the column values. We don't have any aggregate function for product as we have SUM() for addition.
e.g.
SampleTable







COL1COL2
A100
A33
B2
B3
B4
C6


Result

>





COL1PROD
A3300
B24
C6



Solution: -

We will use some basic mathematics to resolve this
i.e. Log(A * B) = Log A + Log B

so it is simple now :-)


SQL :

SELECT Col1, exp(sum(log(col2))) as PROD
FROM SampleTable
Group BY COL1;

ORACLE :

SELECT Col1, exp(sum(log(10,col2))) as PROD
FROM SampleTable
Group BY COL1;