If we have a table like this:
Grp Value
Grp1 2
Grp1 5
Grp1 3
Grp2 3
Grp2 -5
Grp2 -2
Grp3 4
Grp3 0
Grp3 1
Grp4 -2
Grp4 -4
Grp5 7
Grp5 NULL
Grp6 NULL
Grp6 NULL
Grp7 -1
Grp7 10
How can we group/multiply to get this?
GrpID Value
Grp1 30
Grp2 30
Grp3 0
Grp4 8
Grp5 7
Grp6 NULL
Grp7 -10
Multiplying row values is the same as adding logarithms of row values
The trick is dealing with zeros and nulls.
Ok, checked now
At does annoy me that there is no Multiply / Product aggregate function in SQL server. Unfortunately I didn't find the answer @gbn gave above until I'd already solved the problem a different way. I'm posting this alternative solution just in case it helps anyone, or if it turns out to be more efficient.
My solution basically involves using a recursive common table expression to multiply all the values together.
Starting table (+ the partitioned row number) selects to:
List of ID / Multipliers all multiplied together selects to:
This comes from CodePlex "Aggregate Product function extends SQL". I modified the statement to return the desired results except for the NULL group, it returns "1".
ref: http://productfunctionsql.codeplex.com/