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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With