繁体   English   中英

如何在子查询中使用主查询中的列?

[英]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_IdI.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM