我在mysql中有以下表格:
salesinvoices (包含发票号,分类帐和日期)
salesinvoiceitems (带发票号码)
付款(包含发票编号,分类帐和日期)
现在我需要使用税收计算等(表格中包含的列)计算salesinvoiceitems表中针对特定ledgerid的特定invoiceNumber的总金额。
然后我有一张付款表,用于维护日期明确针对特定发票的所有付款记录。此表还包含发票编号和分类帐ID。
我需要为显示最终余额的特定分类帐ID生成报告。我对此类查询毫无头绪。请详细说明。
答案 0 :(得分: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