我有以下表格架构
我想要做的是使用以下汇总总计返回所有发票
SUM(UnitPrice * Qty)
)SUM(Amount)
)鉴于发票可以在没有任何行项目或附加成本的情况下存在,我认为我需要做的就是使用LEFT OUTER JOIN
即
SELECT i.*, SUM(li.UnitPrice * li.Qty) As [Sub Total], SUM(ac.Amount) As [AdditionalCosts]
FROM Invoice i
LEFT OUTER JOIN LineItem li ON li.InvoiceId = i.Id
LEFT OUTER JOIN AdditionalCost ac ON ac.InvoiceId = i.Id
GROUP BY i.Id
然而,问题在于,如果两个子表的长度不同(例如,我有4个行项目,但只有1个额外成本),额外成本的数据会在额外的行项目行中重复(反之亦然) ,您可以通过删除GROUP BY
来验证这一点。
所以会有效地发生以下记录
Invoice
-------
400001
LineItem
---------
400001 | 2000 | 100 | 1
400001 | 2001 | 50 | 2
400001 | 2002 | 10 | 10
400001 | 2003 | 20 | 5
AdditionalCost
--------------
1 | 400001 | 30
2 | 400001 | 70
我的结果集看起来像
Id | Sub Total | Additional Costs
--------------------------------------
40001 | 800 | 400 <-- this should be 100
如何独立计算每个表的SUM
并将它们合并为一个主记录?
答案 0 :(得分:5)
这应该有效:
SELECT i.*, li.[Sub Total], ac.[AdditionalCosts]
FROM Invoice i
LEFT OUTER JOIN (SELECT InvoiceID, SUM(UnitPrice*Qty) As [Sub Total]
FROM LineItem
GROUP BY InvoiceID) li
ON li.InvoiceId = i.Id
LEFT OUTER JOIN (SELECT InvoiceID, SUM(Amount) As [AdditionalCosts]
FROM AdditionalCost
GROUP BY InvoiceID) ac
ON ac.InvoiceId = i.Id