TSql:加入麻烦

时间:2014-04-02 17:18:06

标签: sql-server tsql

我正在尝试编写连接查询,但似乎无法将其过滤掉。我正在选择发票表和应用付款表。我想获得所有发票总额金额的余额 - 应用金额。我可以使用金额来获取应用金额,但是当我尝试获取总发票金额时,它太高了,因为如果已经应用了多个付款,它会提取多个发票结果。

我的结果:

Invoice No | Amount | Paid
----------------------------
      1    |   10   | 5
      1    |   10   | 2
      2    |   50   | 50

如何选择唯一发票编号的总发票金额?。

查询概述:

Select sum(invoiceamount) - sum(appliedamount) as balance
FROM invoice
LEFT JOIN invoicepayments ON invoice.invoiceid = invoicepayments.invoiceid

2 个答案:

答案 0 :(得分:1)

您实际上正在寻找GROUP BY的简单使用方法。您希望将每个结果分组为相同的发票/金额,然后从您要分组的金额中减去该组的付费列的总和(SUM)。

SELECT SUM(balance) FROM
(
SELECT invoiceamount - SUM(appliedamount) as balance
FROM invoice
GROUP BY invoiceid, invoiceamount
) balances

答案 1 :(得分:0)

您可以使用CTE执行此操作,首先计算每张发票上支付的金额,然后将其加入发票,以确定每张发票需要支付的费用。

;WITH   InvoicePay
          AS (
               SELECT invoiceid
                   ,SUM(appliedamount) AS totalpaid
                FROM invoicepayments
                GROUP BY invoiceid
             )
    SELECT i.invoiceID
           ,i.invoiceamount - totalpaid as Balance
        FROM Invoice AS i
        JOIN InvoicePay AS ip
            ON i.invoiceid = ip.invoiceid