我有一个Customer表和一个Payment表,它们连接在一个客户ID(CID)上。在付款表中有一个金额列;有些行有正数(他们欠钱),但其他行有负数(他们付钱)。
我想知道哪些客户,当我总结他们的正面和负面数额时,仍然欠我钱。
如果我只想看到他们的余额,我可以这样做:
SELECT Customer.FirstName, Customer.LastName, Customer.AccountNumber, SUM(Amount) As Balance
FROM Customer
JOIN Payment
ON Customer.CID = Payment.CID
GROUP BY Customer.AccountNumber
如何更改此项,以便如果余额为0或更少,我不会为该客户返回一行?
编辑:HAVING
是我不知道的关键字。感谢您的正确答案!
答案 0 :(得分:2)
SELECT Customer.FirstName, Customer.LastName, Customer.AccountNumber, SUM(Amount) As Balance
FROM Customer
JOIN Payment
ON Customer.CID = Payment.CID
GROUP BY Customer.AccountNumber
HAVING Balance>0
答案 1 :(得分:2)
HAVING关键字允许您根据功能分组进行选择:
SELECT Customer.FirstName, Customer.LastName, Customer.AccountNumber, SUM(Amount) As Balance
FROM Customer
JOIN Payment
ON Customer.CID = Payment.CID
GROUP BY Customer.AccountNumber
HAVING SUM(Amount) > 0
答案 2 :(得分:1)
SELECT c.FirstName, c.LastName, c.AccountNumber, p.Amount AS Balance
FROM Customer c
JOIN Payment p
ON c.CID = p.CID
GROUP BY c.AccountNumber
HAVING SUM(p.Amount) > 0
答案 3 :(得分:0)
select customers.name, sum(payments.amount) balance
from customers join payments on customers.id = payments.cid
group by customers.id having balance > 0