-1

I want to build a sum out of two columns which are factors of a multiplication. Please see the sample data:

+------------+-------------+
| Amount     | Rate        |
+------------+-------------+
|  8         |         4.1 |
|  3         |         2.5 |
|  7         |         5.3 |
+------------+-------------+

so I have this table and I am struggling with the total amount of these results of the multiplication. I could have built a third column and calculate (8*4.1)+(3*2.5)+(7*5.3)

but instead I want to do it directly out of the two columns. So far I used

sum(amount) * sum(rate) 

but it doesn't give me the right results. Can anyone please help me and tell me what the right formula is?

Thank you very much!

3
  • 8
    it should be sum(amount*rate) Commented Aug 22, 2018 at 13:58
  • 4
    You do realize that (8*4.1)+(3*2.5)+(7*5.3) is not the same as (8 + 3 + 7) * (4.1 * 2.5 * 5.3), right? Commented Aug 22, 2018 at 13:59
  • 2
    It's not wrong, you did something wrong on your end. Based on that sample data, sum(amount*rate) will result in 77.4. Here's a demo: rextester.com/ZZGR90732
    – S3S
    Commented Aug 22, 2018 at 14:12

2 Answers 2

6

With sum(amount) * sum(rate) you are multiplying the values after they are summed. To sum the multiplied values you need to use sum(amount * rate)

6
  • Well I am looking for the result of 77.4 but sum(amount*rate) gives me 214.2. So it's wrong. Commented Aug 22, 2018 at 14:06
  • 1
    Are you sure that the values in that you posted are exactly like your data?
    – Kevin K.
    Commented Aug 22, 2018 at 14:07
  • That's such a sample. But I am looking for the correct mathematical operation in order to apply the appropriate formula. Commented Aug 22, 2018 at 14:09
  • 1
    That code will give you 77.4 @not_ur_avg_cookie. declare @table table (Amount int, Rate decimal(2,1)) insert into @table values (8,4.1), (3,2.5), (7,5.3) select sum(Amount * Rate) from @table. I'm not sure how you are getting 214.2.: rextester.com/ZZGR90732
    – S3S
    Commented Aug 22, 2018 at 14:11
  • 1
    But sum(amount * rate) IS the appropriate formula. And using your sample data it DOES return 77.4. 214.20 is the original (and incorrect) formula you posted originally. Several people have already pointed out that it is incorrect.
    – Sean Lange
    Commented Aug 22, 2018 at 14:12
3

Maybe this ...

sum(amount*rate)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.