SQL Select语句与嵌套group by子句

时间:2013-06-08 02:18:28

标签: sql oracle

我有2张桌子。我需要从Invoices中选择名称为balance_due的列名和计算字段。

查询的结果应该是所有记录组合的名称及其余额。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

或者还有另一种语法:

;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