我有这个问题:
Select I.Invoice_Number, PA.Invoice_Number, I.Line_Amount, PA.Invoiced_Amount
from XXX as PA
Left join (select Invoice_Number, Line_Amount from Invoices) as I
on PA.Invoice_Number = I.Invoice_Number
Group by PA.Invoice_Number;
两者都应该为每个Invoice_Number提供相同数量的成本(I.Line_Amount = PA.Invoice_Amount),但是I.Line_Amount只会带来列表中的第一行,而PA.Invoiced.Number带来成本的总和在那张发票上。
我尝试在子查询中使用sum(Line_Amount),但所有记录都显示为Null。
我是否有办法加入这两个表并确保每张发票的金额与该发票的总金额相符?
谢谢!
答案 0 :(得分:0)
如果我理解正确(并且您想确保Line_Amount
表中Invoices
的总和与Invoiced_Amount
表中的XXX
相同,那么第二个表应该有发票号和金额总和:
select I.Invoice_Number, PA.Invoice_Number, I.total, PA.Invoiced_Amount
from XXX as PA
left join (
select Invoice_Number, sum(Line_Amount) as total
from Invoices
group by Invoice_Number
) as I
on PA.Invoice_Number = I.Invoice_Number
您可以在此处试用:http://sqlfiddle.com/#!9/d1d010/1/0