简体   繁体   English

SQL减去不同表上的两列

[英]SQL Subtract two columns on different tables

I have two tables, Customer, and Invoices,I have to list all the customers with their remaining credit. 我有两个表,Customer和Invoices,我必须列出所有剩余信用额的客户。 I'm trying to subtract the sum of the Invoice Amount column from the CreditLimit column to give me the remaining credit? 我正在尝试从CreditLimit列中减去“发票金额”列的总和,以便给我剩余的信用额?

桌子

This is my query so far 到目前为止,这是我的查询

DECLARE @CreditRemaining INT

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

Use a derived table for the invoice amount SUM() , then JOIN back to Customer: 使用派生表的发票金额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

As others mentioned, this is assuming you are limiting your selection to one customer. 正如其他人提到的那样,这是假设您将选择限制为一个客户。

For all customers, just use a select: 对于所有客户,只需使用以下选择:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM