从两个表中求和并与第三个表中的值进行比较

时间:2017-05-06 11:05:48

标签: sql sql-server select

我正在尝试做一些我认为非常简单但却无法在SQL语句中弄明白的事情。 表格

  1. 发票(列 - GrossAmount)

  2. 收据(列 - 收据价值,可能有收据或根本没有收据)

  3. 信用票据(列 - GrossCredit,可能有信用票据或无信用证)

  4. 我想显示未结帐单总额,即显示Invoices.GrossAmount > (sum(Receipt.ReceiptValue) + sum(CreditNotes.GrossCredit))所有发票。

    查询需要显示所有未完全支付或根本未支付的发票。

    InvoiceId在所有表中都与外键相同。

    使用MS SQL Server 2014。

2 个答案:

答案 0 :(得分:1)

您需要单独对每个表进行求和(按发票分组),然后[左]加入结果:

SELECT i.InvoiceId
FROM   invoices i
LEFT JOIN (SELECT   InvoiceId, SUM(ReceiptValue) AS sum_receipt
           FROM     receipts
           GROUP BY InvoiceId) r ON i.InvoiceId = r.InvoiceId
LEFT JOIN (SELECT   InvoiceId, SUM(GrossCredit) AS sum_credit
           FROM     credit
           GROUP BY InvoiceId) g ON i.InvoiceId = g.InvoiceId
WHERE     i.GrossAmount > COALESCE(sum_receipt, 0) + COALESCE(sum_credit, 0)

答案 1 :(得分:0)

我想你想要这样的东西:

select i.*,
       coalesce(r.sumrv, 0) as receiptValue,
       coalesce(c.sumgc, 0) as grossCredits
from invoices i left join
     (select invoiceId, sum(receiptvalue) as sumrv
      from receipts
      group by invoiceId
     ) r
     on i.invoiceId = r.invoiceId left join
     (select invoiceId, sum(grosscredit) as sumgc
      from credits c
      group by invoiceId
     ) c
     on i.invoiceId = c.invoiceId 
where i.GrossAmount > coalesce(r.sumrv, 0) + coalesce(c.sumgc, 0);

三件重要的事情:

  • 使用left join,这样就不会删除一个或两个表中没有匹配记录的发票。
  • 使用coalesce(),以便将NULL值视为0
  • 在加入表格之前进行聚合