

We can do a much better job with a little algebra and logic: I present this version of the query first because this is how I developed the answer. The SUM() counts the -1 results then the MOD() functions determines if the count was odd or even. The innermost CASE expression uses a SIGN() function which returns + 1 for a positive number, -1 for a negative number and 0 for a zero. The third CASE expression will return minus one if there was an odd number of negative numbers in the nbr column. The MIN(ABS(nbr)) is a handy trick for detecting the existence of a zero in a list of both positive and negative numbers with an aggregate function. The second CASE expression will return zero as the answer if there was a zero in the nbr column of any selected row. The first CASE expression is to ensure that all zeros and negative numbers are converted to a non-negative or NULL for the SUM() function, just in case your SQL raises an exception. It is worth studying the three CASE expressions that make up the terms of the Prod calculation. You should watch the data type of the column involved and use either integer 0 and 1 or decimal 0.00 and 1.00 as is appropriate in the CASE statements. The nice part of this is that you can also use the SUM (DISTINCT ) option to get the equivalent of PRD (DISTINCT ).
#Aggregate date up to a date sql mod
* (CASE WHEN MOD (SUM (CASE WHEN SIGN(nbr) = -1 SELECT ((EXP (SUM (LN (CASE WHEN nbr = 0.00 The expression for the product of a column from logarithm and exponential functions is:

Likewise, the Standard also defines the exponential function as EXP() as its inverse. But some older SQL might return a zero or a NULL. Since the logarithm of zero or less is undefined, the Standard requires an exception to be raised.

The Standard allows only natural logarithms shown as LN(), but you will see LOG10() for the logarithm base ten and perhaps LOG(, ) for a general logarithm function. The nice part of this solution is that you can also use the DISTINCT option in the SUM() function.īut there are a lot of warnings about this approach. Roy Harvey, another SQL guru who answered questions on CompuServe, found a different solution, which only someone old enough to remember slide rules and that we can multiply by adding logs. The PRD() Aggregate Function by Logarithms Here is a “cut & paste” from one of my books:Ģ9.06.02.

Our original problem can thus be solved very easily using this, as shown in my stack overflow answer: So, we can define any multiplication in terms of a bunch of exponentiation to some base (say e) and logarithms to some base (say e). Check out this cool Wikipedia website about logarithmic identities, which we are going to blindly trust.
