0

如何使用 Balance 列的 where 子句过滤以下查询中的数据。当我在 where 条件下使用 Balance 时,出现错误 [“where 子句”中的未知列“Balance”]。

select *,(it.Total - p.Amount) as Balance
from invoices i
left outer join invoice_items it
    on i.ID=it.InvoiceID
left outer join payment p
    on p.InvoiceID=it.InvoiceID 
where Balance!=0;

而且,当没有找到匹配的付款记录时,我不需要在 Balance 列中显示空值,而是需要 invoice_items 表的 Total 值。

4

2 回答 2

1

您不能在 where 子句中使用别名。

改写

where (it.Total - p.Amount) <> 0

而对于另一部分

  select 
   (case when p.PaymentId IS NULL 
    then it.Total
    else
    (it.Total - p.Amount) 
   end)

或者。COALESCE 表示:如果 p.Amount 为空,则使用 0。否则使用 p.Amount

select it.Total - COALESCE(p.Amount, 0)

最后

select i.*,(it.Total - COALESCE(p.Amount, 0)) as Balance
from invoices i
left outer join invoice_items it
    on i.ID=it.InvoiceID
left outer join payment p
    on p.InvoiceID=it.InvoiceID 
where it.Total - COALESCE(p.Amount, 0) <> 0;
于 2012-09-18T08:20:34.663 回答
0

试试这个:

select *,(it.Total - p.Amount) as Balance
from invoices i
left outer join invoice_items it
    on i.ID=it.InvoiceID
left outer join payment p
    on p.InvoiceID=it.InvoiceID 
where (it.Total - p.Amount) <> 0;

您不能在 where 子句中使用别名,因为按时间顺序,WHERE 发生在 SELECT 之前,它始终是执行链中的最后一步。

于 2012-09-18T08:21:34.383 回答