2013-05-29 45 views
0

我已經在MySQL以下表:複雜的查詢,用於生成報告datewise

salesinvoices(與發票號,ledgerid和日期)

salesinvoiceitems(與發票數)

付款(帶發票號碼,ledgerid和日期)

現在我需要d通過使用稅收等的計算(表中包含的列)來計算salesinvoiceitems表與特定ledgerid的特定發票號的總金額。

然後我有一張付款表,它可以明確記錄所有對特定發票付款的記錄。此表還包含發票號碼和分類帳編號。

我需要爲顯示結尾餘額的特定分類賬編號生成報告。我對這樣的問題毫無頭緒。請說明一下。

+0

我可以建議將您的架構放在http://sqlfiddle.com/上以獲得更清晰一點嗎? – Samsquanch

回答

0

我假設您的salesinvoiceitems表中有一個「金額」字段,以便我們可以計算每張發票的項目金額總和。在下面的示例中,我稱該列爲「item_amt」。我們可以嘗試做這樣的事情......

select ledgerid , sum(balance) as total_balance 
from 
-- sub query to calculate balance per invoice and ledgerid 
(
select distinct 
invoices.invoice_number, 
invoices.ledgerid, 
tot_item_amt, 
tot_payment_amt, 
(tot_item_amt - tot_payment_amt) as balance 
from salesinvoices as invoices 
-- sub query to get the sum of all the items on an invoice 
inner join (select invoice_number, sum(item_amt) as tot_item_amt from salesinvoiceitems group by invoice_number) as items on invoices.invoice_number = items.invoice_number 
-- sub query to get the sum of all the payments made against an invoice 
inner join (select invoice_number, sum(payment_amt) as tot_payment_amt from payments group by invoice_number) as payments on invoices.invoice_number = payments.invoice_number 
) t 
-- sum balance and group by ledgerid 
group by ledgerid