SELECT
dbo.Customers.FirstName as Firstname, dbo.Customers.LastName as Lastname,
dbo.Customers.Phone as Phone, dbo.Guarantors.FirstName as Guarantor Firstname,
dbo.Guarantors.LastName as Guarantor Lastname,
dbo.Guarantors.Phone as Guarantor Phone,
SUM(dbo.PaymentHistory.PaymentAmount) - SUM(dbo.PaymentHistory.PayedAmount) as Debt
FROM
dbo.Credits
INNER JOIN
dbo.PaymentHistory ON dbo.Credits.ID = dbo.PaymentHistory.CreditID
INNER JOIN
dbo.Customers ON dbo.Credits.CustomerID = dbo.Customers.ID
LEFT OUTER JOIN
dbo.CreditGuarantors ON dbo.Credits.ID = dbo.CreditGuarantors.CreditID
LEFT OUTER JOIN
dbo.Guarantors ON dbo.CreditGuarantors.GuarantorID = dbo.Guarantors.ID
WHERE
(dbo.Credits.Status = 0) AND
(dbo.PaymentHistory.PaymentDay <= GETDATE()) AND
(dbo.Credits.BranchID = 1)
GROUP BY
dbo.Customers.LastName, dbo.Customers.Phone,
dbo.Credits.ID, dbo.Customers.FirstName,
dbo.Guarantors.FirstName, dbo.Guarantors.LastName,
dbo.Guarantors.Phone
所以我想再添加一条规则where Debt !=0
。但我得到了错误,你可以帮我吗?我想得到不是0的债务,有债务的人姓
答案 0 :(得分:3)
使用HAVING
子句。将其添加到查询的末尾:
HAVING SUM(dbo.PaymentHistory.PaymentAmount) - SUM(dbo.PaymentHistory.PayedAmount) <> 0
答案 1 :(得分:2)
因为这涉及聚合函数,所以您希望使用HAVING
子句:
HAVING SUM(dbo.PaymentHistory.PaymentAmount) - SUM(dbo.PaymentHistory.PayedAmount) <> 0
或者:
HAVING SUM(dbo.PaymentHistory.PaymentAmount) <> - SUM(dbo.PaymentHistory.PayedAmount)
注意:如果您使用表别名,您的查询将更容易编写和读取。