选择客户所有车辆的总账面价值 (SQL)
我有以下数据库架构(Microsoft SQL Server Compact Edition):
如何选择一条或多条客户记录,是否有一个附加字段包含客户拥有的所有车辆的总账面价值?我尝试了类似的操作:
SELECT Customers.ID, Customers.FirstName, ..., SUM(Receipts.BookValue) FROM Customers INNER JOIN Vehicles ON Vehicles.CustomerID = Customers.ID INNER JOIN Receipts ON Receipts.VehicleID = Vehicles。 ID;
但没有成功。我想我可能需要 GROUP BY 之类的东西?
I have the following database schema (Microsoft SQL Server Compact Edition):
How can I select a customer record or customer records, with an additional field containing the total book value of all vehicles owned by the customer? I tried something like:
SELECT Customers.ID, Customers.FirstName, ..., SUM(Receipts.BookValue) FROM Customers INNER JOIN Vehicles ON Vehicles.CustomerID = Customers.ID INNER JOIN Receipts ON Receipts.VehicleID = Vehicles.ID;
but was unsuccessful. I'm thinking I might need a GROUP BY or something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
另请注意,当使用 Sum 等聚合时,您必须确保所有附加字段都是聚合类型的一部分或在 GROUP BY 列表中。
有时进行 2 个查询更容易,内部查询执行所有求和,其余查询显示附加信息,如下所示:
Also please note that when using aggregates like Sum you must ensure that all additional fields are part of an aggregate type or in the GROUP BY list.
Sometimes its easier to make 2 queries, the inner query does all the summing and the rest displays additional info like this:
是的,您需要一个 GROU BY
<不是聚合的每列的列表>
(SUM、COUNT 等)Yes, you need a GROU BY
<list of every column that is not an aggregate>
(SUM, COUNT, etc.)如果您想要账面价值聚合和所有客户字段。像这样的东西会起作用
If you want the book value aggregate and all the customer fields. Something like this will work