Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiply rows in t-sql

I have following table

 ID     Number    
----------------     
   1       41.5
   2       42.5
   3       43.5
   2       44.5   
   2       45.5
   1       46.5
   1       47.5

I need to write a query which will return distinct ID's and corresponding Number column values multiplied. For the given table result should be like this

ID       Result 
-----------------
  1         41.5 * 46.5 * 47.5
  2         42.5 * 44.5 * 45.5
  3         etc...

(without use cursors)

like image 633
Nario Avatar asked Nov 18 '11 16:11

Nario


1 Answers

SELECT Id, EXP(SUM(LOG(Number))) as Result
FROM Scores 
GROUP BY id

This will work for positive numbers, to multiply negative numbers as well you can use ABS() function to use absolute (positive) value but final result will be positive rather than negative number:

SELECT Id, EXP(SUM(LOG(ABS(Number)))) as Result
FROM Scores 
GROUP BY id

EDIT: Added test script

DECLARE @data TABLE(id int, number float)

INSERT INTO @data VALUES
(1, 2.2),
(1, 10),
(2, -5.5),
(2, 10)

SELECT Id, EXP(SUM(LOG(ABS(Number)))) as Result 
FROM @data GROUP BY id 

Output:

1   22
2   55
like image 126
sll Avatar answered Sep 27 '22 18:09

sll