MySQL 中具有相似 ID 的行的列乘积之和

发布于 2024-10-13 00:07:34 字数 849 浏览 1 评论 0原文

我在名为“购买”的表中有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

懵少女 2024-10-20 00:07:34
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
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
泅人 2024-10-20 00:07:34

@sombe:我刚刚测试了你的查询,它工作得很好。你确定你的mysql是最新的吗?

alt text

第二个也可以正常工作:

@sombe: I've just tested your query and it works just fine. Are you sure your mysql is up to date?

alt text

The second works fine too:

alt text

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文