[英]How to use column from main query in subquery?
我有一個表總帳的發票。 然后我有一個表格付款與列數量(通常有幾個付款到一張發票)。 我需要一個列余額,這是Invoice.Total的差異 - (在該發票上支付的總額)。 這就是我所擁有的(哦,你使用Azure Sql Server)
select I.Invoice_Id,
I.Total - (select sum(Amount) from Payments P
where I.Invoice_Id = P.Invoice_Id) as Balance,
Q.Quote_Id,
Q.Description,
Q.Vendor_Num
from Invoice as I
inner join Payments as P on I.Invoice_Id = P.Invoice_Id
inner join Quote as Q on Q.Quote_Id = I.Quote_Id;
最終,這將是一個視圖,顯示發票的余額。 如果我刪除子查詢中的where,它會給我一個答案,但它是所有付款的總和。 我只想要在該發票上支付的款項。 任何幫助,將不勝感激。
謝謝
我懷疑您的查詢返回多個結果(每次付款重復),因為您要joining
payments
表。
一種選擇是將該join
刪除到payments
表。 這是一個替代選項,它將correlated subquery
移動到join
:
select I.Invoice_Id,
I.Total - p.SumAmount as Balance,
Q.Quote_Id,
Q.Description,
Q.Vendor_Num
from Invoice as I
inner join Quote as Q on Q.Quote_Id = I.Quote_Id;
inner join (
select invoice_id, sum(amount) SumAmount
from Payments
group by invoice_id) as P on I.Invoice_Id = P.Invoice_Id
這有兩種方法。 您可以子查詢或分組。 如果您正在執行子查詢,則不需要主查詢中的表。 此外,付款的內部聯接意味着查詢不會返回未付款的發票。 如果I.Invoice_Id = P.Invoice_Id
, I.Invoice_Id = P.Invoice_Id
其更改為Group By示例中的左外連接將返回NULL行。
通過...分組:
SELECT I.Invoice_Id,
I.Total - sum(ISNULL(P.Amount,0)) AS Balance,
Q.Quote_Id,
Q.Description,
Q.Vendor_Num
FROM Invoice AS I
JOIN Quote AS Q on Q.Quote_Id = I.Quote_Id
LEFT JOIN Payments AS P on I.Invoice_Id = P.Invoice_Id
GROUP BY I.Invoice_Id, I.Total, Q.Quote_Id, Q.Description, Q.Vendor_Num
子查詢:
SELECT I.Invoice_Id,
I.Total - (SELECT ISNULL(SUM(Amount),0) FROM Payments P WHERE P.Invoice_Id = I.Invoice_Id) AS Balance,
Q.Quote_Id,
Q.Description,
Q.Vendor_Num
FROM Invoice AS I
JOIN Quote AS Q on Q.Quote_Id = I.Quote_Id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.