2012-12-19 48 views
0

我有兩個表。通過客戶端獲取待定發票

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 

所以我不知道如何獲得待定/部分支付的發票。

任何人都可以幫忙。

+0

啓動和未掛起和部分所許發票。這些可以是完全不同的類別。 – SWeko

回答

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 
+0

它只給出發票ID'6'的結果,但是'5和7'怎麼樣??? –

+0

@VishalSuthar:這選擇未付清的發票。過濾器通過底部「Where(total_Price - amountPaid)> 0」完成。如果您需要查看全部內容,請將其註釋掉。 – Kaf

+0

@VishalSuthar:我已經完成了一項編輯工作,以支付根本沒有支付的發票。用'Isnull()'檢查。現在應該沒問題。 – Kaf

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