带求和的 Sql 子查询
我有两张表:发票和付款。发票有付款。我想编写一个查询来显示未付发票和发票剩余金额,这是通过总结发票付款并从发票金额中减去它来计算的。我尝试了这个查询,但它不起作用。请问我该怎么做。
SELECT Invoice.[Invoice Date], Invoice.Item, Invoice.Quantity,
Invoice.[Unit Price],
Invoice.[Payment Status], Invoice.[LongDate],
Invoice.Quantity*Invoice.[Unit Price] - Sum(Q.Amount) AS Remaining
FROM
(SELECT Invoice.[Invoice Id], [Payment ID]
FROM Invoice
INNER JOIN Payment ON Invoice.[Invoice Id] = Payment.[Invoice Id]) AS Q
INNER JOIN Invoice ON Q.[Invoice Id] = Invoice.[Invoice Id]
GROUP BY Invoice.[Invoice Id];
I have two tables Invoices and Payments. invoices have payments. I want to write a query that displays unpaid invoices and the remaining amount of the invoice, which is calculated by summing up the payments of the invoice and subtracting it from the invoice amount. I tried this query but it doesn't work. please how can i do it.
SELECT Invoice.[Invoice Date], Invoice.Item, Invoice.Quantity,
Invoice.[Unit Price],
Invoice.[Payment Status], Invoice.[LongDate],
Invoice.Quantity*Invoice.[Unit Price] - Sum(Q.Amount) AS Remaining
FROM
(SELECT Invoice.[Invoice Id], [Payment ID]
FROM Invoice
INNER JOIN Payment ON Invoice.[Invoice Id] = Payment.[Invoice Id]) AS Q
INNER JOIN Invoice ON Q.[Invoice Id] = Invoice.[Invoice Id]
GROUP BY Invoice.[Invoice Id];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
当然,您还需要将其他列添加到选择中,但我认为它们与这个问题无关,所以为了清楚起见,我省略了它们。
这是我用来测试这个的一些测试数据:
以及使用这些数据的结果:
Try this:
Of course you will also need to add the other columns to the select too, but I don't think they are relevant to this question so I omitted them for clarity.
Here is some test data I used to test this:
And the result with this data:
编辑:我假设,您在结果中不需要项目相关信息。
使用
LEFT JOIN
时假设发票可能没有付款记录。EDIT: I am assuming, you won't need Item related information in the result.
LEFT JOIN
is used with an assumption that Invoice might not have a Payment record.