我有一个查询来从数据库中检索未付款项,即总发票金额减去总付款金额。问题是,当没有发票付款时,这些只是不显示。我希望这些发票金额显示,其总付款金额为零。这是我的疑问:
SELECT DISTINCT Client.FirstName + ' ' + Client.LastName AS
[Client Name],
SUM(Invoices.InvoiceAmount) AS
[Total Invoice Amounts],
SUM(ClientPayments.PaymentAmount) AS
[Total Amount Paid],
SUM(Invoices.InvoiceAmount - ClientPayments.PaymentAmount) AS
[Outstanding Payment Amount]
FROM Invoices
INNER JOIN ClientPayments
ON Invoices.InvoiceNumberID = ClientPayments.InvoiceNumberID
INNER JOIN Client
ON Invoices.ClientNumberID = Client.ClientNumberID
GROUP BY Client.FirstName,
Client.LastName
谢谢, 艾米
答案 0 :(得分:2)
尝试将INNER JOIN
更改为LEFT JOIN
以进行查询中的第一次加入
答案 1 :(得分:2)
它可能是基于进行左连接,但如果您有一张已多次付款的发票(部分付款),您会得到虚假结果吗?那些“Sum”方程式会计算发票金额TWICE ex:每个部分付款一个吗?我会尝试如下。
SELECT
C.ClientNumberID,
C.FirstName + ' ' + C.LastName AS ClientName,
SUM( I.InvoiceAmount ) TotalInvoices,
SUM( CP.PaymentAmount ) AS TotalAmountPaid,
SUM( I.InvoiceAmount ) - SUM( CP.PaymentAmount ) AS OutstandingPaymentAmount
FROM
Invoices I
JOIN Clients C
on I.ClientNumberID = C.ClientNumberID
LEFT JOIN ClientPayments CP
on I.InvoiceNumberID = CP.InvoiceNumberID
GROUP BY
I.ClientNumberID
ORDER BY
C.LastName,
C.FirstName
请注意我的GROUP BY是客户编号...如果您有5个客户“William Smith”或“Robert Brown”可以被视为“通用名称”,那么会发生什么情况。你不想给威廉史密斯一个声明说他欠他5000美元的全部费用,而发票实际上是与其他“威廉史密斯”客户分开的。那么,ORDER BY会把它们放到你需要的任何顺序......或者基于顶部最大收藏的优秀数量下降。