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

时间:2016-08-03 23:39:35

标签: sql sql-server

我有一张表总帐的发票。然后我有一个表格付款与列数量(通常有几个付款到一张发票​​)。我需要一个列余额,这是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,它会给我一个答案,但它是所有付款的总和。我只想要在该发票上支付的款项。任何帮助将不胜感激。

由于

2 个答案:

答案 0 :(得分:0)

我怀疑您的查询返回了多个结果(每次付款重复),因为您在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

答案 1 :(得分:0)

有两种解决方法。您可以子查询或分组。如果您正在执行子查询,则不需要主查询中的表。此外,付款的内部联接意味着查询不会返回未付款的发票。在Group By示例中将其更改为左外连接将在不满足I.Invoice_Id = P.Invoice_Id时返回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