MySQL中具有相似ID的行的列的总和
问题描述:
我在称为购买"的表中有3列:
I have 3 columns in a table called "purchases":
id amount price
2 2 21
2 5 9
3 8 5
我想对所有具有相似ID的行进行分组,并得到以下结果:
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)])
作为具有相同ID的行的总计SUM(金额*价格).
as total accounts for SUM(amount*price) for rows with similar IDs.
我尝试使用
SELECT id, SUM(p.price*p.amount) total FROM purchases p GROUP by p.id
,但效果不佳(即无法实现我想要的功能,这就是我上面写的内容). 关于如何在mysql中执行此操作的任何想法?
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?
查询返回的示例:
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]
答
SELECT
id,
SUM(amount*price) AS total
FROM mytable
GROUP BY id
数据:
| id | amount | price |
|----|--------|-------|
| 2 | 3 | 19 |
| 2 | 3 | 89 |
| 3 | 203 | 1 |
结果:
id total
2 324
3 203