Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of multiplication of columns for rows with similar IDs in MySQL

Tags:

select

mysql

sum

I have 3 columns in a table called "purchases":

id         amount         price
2          2              21
2          5              9
3          8              5

I want to group all rows with similar IDs and have this array as a result:

array([0] => [id => 2, total => 87 (because 2*21+5*9=87)], [1] => [id => 3, total => 40 (because 8*5=40)])

as total accounts for SUM(amount*price) for rows with similar IDs.

I've tried using

SELECT id, SUM(p.price*p.amount) total FROM purchases p GROUP by p.id

but it doesn't work well (i.e. it doesn't achieve what I want, which is what I wrote above). Any ideas on how to do this in mysql?

An example of what the query returns:

    id         amount         price
    2          3              89
    2          3              19

    SELECT id, SUM(p.price*p.amount) total FROM purchases p GROUP by p.id

==> [id => 2, total => 183]
like image 650
Gal Avatar asked Jan 17 '11 10:01

Gal


People also ask

How can I sum rows with same ID in SQL?

To sum rows with same ID, use the GROUP BY HAVING clause.

How do you multiply columns in MySQL?

All you need to do is use the multiplication operator (*) between the two multiplicand columns ( price * quantity ) in a simple SELECT query. You can give this result an alias with the AS keyword; in our example, we gave the multiplication column an alias of total_price .


1 Answers

SELECT
id, 
SUM(amount*price) AS total
FROM mytable
GROUP BY id

Data:

| id | amount | price |
|----|--------|-------|
| 2  | 3      | 19    |
| 2  | 3      | 89    |
| 3  | 203    | 1     |

Result:

id  total
2   324
3   203
like image 198
Vincent Mimoun-Prat Avatar answered Oct 08 '22 13:10

Vincent Mimoun-Prat