SQL在不同的表上减去两列

时间:2017-06-09 14:04:19

标签: sql sql-server

我有两个表,即客户和发票,我必须列出所有客户的剩余信用。我试图从CreditLimit列中减去发票金额列的总和,以便给我剩余的信用额度?

Tables

这是我目前的查询

DECLARE @CreditRemaining INT

SELECT 
   @CreditRemaining = (c.CreditLimit - SUM(i.Amount))
FROM 
     Customer c 
INNER JOIN 
     Invoices i on
     c.ID = i.customerId

1 个答案:

答案 0 :(得分:4)

将衍生表用于发票金额SUM(),然后将JOIN用于客户:

DECLARE @CreditRemaining INT

SELECT @CreditRemaining = (c.CreditLimit - TotalSpent)
FROM Customer c
INNER JOIN (SELECT SUM(Amount) TotalSpent, CustomerID
            FROM Invoices
            GROUP BY CustomerID) i ON i.CustomerID = c.ID

正如其他人所说,这是假设您将选择限制为一个客户。

对于所有客户,只需使用选择:

SELECT C.Name, (c.CreditLimit - TotalSpent) CreditRemaining
FROM Customer c
INNER JOIN (SELECT SUM(Amount) TotalSpent, CustomerID
            FROM Invoices
            GROUP BY CustomerID) i ON i.CustomerID = c.ID
GROUP BY C.Name