gpt4 book ai didi

MySQL - 跨多个表的算术

转载 作者:行者123 更新时间:2023-11-28 23:08:19 24 4
gpt4 key购买 nike

假设我有两个表,PeopleInvoices

firstname    postcode
Alex 2403
Peter 2357
Michael 3456

发票

person       earned
Alex 12300
Alex 3556
Peter 1000
Alex 234
Michael 10000

我想向人们添加一个名为收入的列,显示每个人的总收入 - 我该如何实现?

我认为应该连接这些表:

INNER JOIN Invoices ON People.firstname = Invoices.person

但我不确定如何将赚取的钱相加并分组为相应的收入(我假设在某处使用了 COUNT(*))。

最佳答案

依赖“firstname”和“person”作为连接显然非常不稳定,因为名称不是唯一的,但假设您使用的是任意数据示例:

select p.firstname, p.postcode, sum(i.earned) earnings from people p
inner join invoices i on p.firstname = i.person
group by i.person

给予

| *firstname* | *postcode* | *earnings* |
+-------------+------------+------------+
| Alex | 2403 | 16090 |
| Michael | 3456 | 10000 |
| Peter | 2357 | 1000 |

也许不是最受人尊敬的资源,但此链接应该有助于了解有关将 GROUP BYSUM 一起使用的更多信息

https://www.w3resource.com/sql/aggregate-functions/sum-with-group-by.php

关于MySQL - 跨多个表的算术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46581084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com