MySQL 中具有相似 ID 的行的列乘积之和
我在名为“购买”的表中有 3 列:
id amount price
2 2 21
2 5 9
3 8 5
我想对具有相似 ID 的所有行进行分组,并得到此数组作为结果:
array([0] => [id => 2, total => 87 (because 2*21+5*9=87)], [1] => [id => 3, total => 40 (because 8*5=40)])
具有相似 ID 的行的 SUM(金额*价格) 的总帐户。
我尝试过使用
SELECT id, SUM(p.price*p.amount) total FROM purchases p GROUP by p.id
,但效果不佳(即它没有达到我想要的效果,这就是我上面写的)。 关于如何在 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]
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]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
数据:
结果:
Data:
Result:
@sombe:我刚刚测试了你的查询,它工作得很好。你确定你的mysql是最新的吗?
第二个也可以正常工作:
@sombe: I've just tested your query and it works just fine. Are you sure your mysql is up to date?
The second works fine too: