具有相关子查询的 SQL Sum()
我有两个表:基金和项目。 Items 有一个名为fundID 的字段,与基金表的ID 相关。物品也有价格字段。
下面是两个表的简化示例:
FUND
ID fundName
1 maintenance
2 books
3 development
4 media
ITEMS
ID price fundID
1 $10 2
2 $20 4
3 $5 4
4 $8 1
5 $10 3
6 $12 4
我想创建一个查询,该查询将提供每个基金的名称以及通过fundID 字段连接到该基金的项目的所有价格总和。我尝试了几种方法,例如在 SUM() 和 WHERE 中使用相关子查询,但出现错误。
如果有人能指出我正确的方向,我将不胜感激。
I have two tables: fund and items. Items has a field called fundID that is related to the ID of the fund table. Items also has a price field.
Here's a simplified example of the two tables:
FUND
ID fundName
1 maintenance
2 books
3 development
4 media
ITEMS
ID price fundID
1 $10 2
2 $20 4
3 $5 4
4 $8 1
5 $10 3
6 $12 4
I want to create a query that will give me the name of each fund and the sum of all prices for items that are connected to that fund through the fundID field. I have tried several methods such as having a correlated subquery within the SUM() and also within the WHERE, and I am getting errors.
If someone could point me in the right direction, I'd appreciate it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
考虑到您的表结构,没有充分的理由这样做,但是问题确实询问了子查询并且表结构得到了简化。
因此,这将给出与直接 JOIN/GROUP BY 相同的结果。
请注意,如果您希望没有项目的资金为 0,则可以使用 COALESCE/LEFT JOIN。
There's no good reason to do it this way given your table structure however the question does ask about a sub query and the table structure is simplified.
So this will give the same results as straightfoward JOIN/GROUP BY
Note the COALESCE/LEFT JOIN is there in case you want 0 for funds that have no items.
试试这个
Try this
如果您有很多资金,基金 ID 可能更好按分组
If you have a lot of funds fund Id is probably better to group by
试试这个:
Try this :