由客户获取待处理发票

时间:2012-12-19 08:27:00

标签: sql-server join

我有两张桌子。

tbl_Invoice

Invoice

tbl_Payment

Payments

我想要的是List of Pending/Partial Invoices特定客户。

我试过的是:

Select * from tbl_Invoice I 
    left join tbl_payment P on (I.client_id = P.client_id 
        AND I.invoice_id <> P.invoice_Id)
    left join tbl_client C on I.client_id = C.client_id
    WHERE I.client_id = 8

但它给了我一些错误的输出。

Invoice No  Client Name Date    details             Amount  Paid
----------------------------------------------------------------
ATPL00001   Vishal  10 Dec,2012 Web Designing       100.00  50.00
ATPL00001   Vishal  10 Dec,2012 Web Designing       100.00  10.00
ATPL00001   Vishal  10 Dec,2012 Web Designing       100.00  100.00
ATPL00001   Vishal  10 Dec,2012 Web Designing       100.00  100.00
ATPL00002   Vishal  07 Dec,2012 Software Development        1000.00

所以我不知道如何获得待付/部分付款发票。

任何人都可以帮忙。!!

2 个答案:

答案 0 :(得分:1)

试试这个(你可以根据需要从发票表中添加更多列到第二个选择查询

;WITH cte (clientid, invoiceid,  amountPaid)
As
(
   Select client_id clientId, invoice_id invoiceId,  sum(amt) amountPaid
   From tbl_Payment
   Where client_id = @YourClientId
   Group by invoice_id, client_id
)
Select client_id, invoice_id, (total_Price - Isnull(amountPaid,0)) toBePaid
From tbl_invoice I Left join cte On I.clinet_id = cte.clientId 
           And I.invoice_id = cte.invoiceid
Where (total_Price - Isnull(amountPaid,0)) > 0

答案 1 :(得分:0)

Select invoice_ID,Client,total_price - Coalesce(AMT,0) as [open]
from
(
select invoice_ID,Client,total_price
,(Select sum(AMT) as AMT from tbl_Payment where tbl_Payment.invoice_ID=tbl_Invoice.invoice_ID) as payed
 from tbl_Invoice left join tbl_client C on tbl_Invoice.client_id = C.client_id
 ) a
 where total_price - Coalesce(AMT,0)>0