我正在尝试做一些我认为非常简单但却无法在SQL语句中弄明白的事情。 表格
发票(列 - GrossAmount)
收据(列 - 收据价值,可能有收据或根本没有收据)
信用票据(列 - GrossCredit,可能有信用票据或无信用证)
我想显示未结帐单总额,即显示Invoices.GrossAmount > (sum(Receipt.ReceiptValue) + sum(CreditNotes.GrossCredit))
所有发票。
查询需要显示所有未完全支付或根本未支付的发票。
InvoiceId在所有表中都与外键相同。
使用MS SQL Server 2014。
答案 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
。