我有 2 张桌子。我需要从 Invoices 中选择列名和一个名为 balance_due 的计算字段。
查询的结果应该是姓名和他们所有记录的余额。
谢谢你的帮助。
SELECT v.vendor_name, i.totalbalance
FROM Vendors as v
INNER JOIN (
SELECT vendor_id, sum(invoice_total-payment_total) as totalbalance
FROM invoices
GROUP BY vendor_id
) as i on i.vendor_id = v.vendor_id
或者还有另一种语法:
;With i As
(
SELECT vendor_id, sum(invoice_total-payment_total) as totalbalance
FROM invoices
WHERE payment_total is not null
GROUP BY vendor_id
)
SELECT Vendors.vendor_name, i.totalbalance
From Vendors LEFT JOIN i ON Vendors.vendor_id = i.vendor_id