您是否需要显示各个费用行以及所有总计?如果没有,您可以按supplierinv 列分组并对金额求和:
select supplierinv, sum(amount) as invoice_amount
from expenses group by supplierinv
然后您可以简单地在客户端添加所有 invoice_amount 值以获得总计。
如果您确实需要每个费用行,您可以相当轻松地在客户端进行发票汇总:
$invtotals = array();
$grand_total = 0;
foreach (getexpenses() as $row) {
$supplierinv = $row['supplierinv'];
if (!array_key_exists($supplierinv, $invtotals)) {
$invtotals[$supplierinv] = 0;
}
$invtotals[$supplierinv] += $row['amount'];
$grand_total += $row['amount'];
}
另一种方法,如果您想显示拆分为发票的表格,只需确保结果按供应商inv 排序,然后:
$grand_total = 0;
$invoice_total = 0;
$current_invoice = -1;
foreach (getexpenses() as $row) {
if ($current_invoice > 0 && $current_invoice != $row['supplierinv']) {
show_invoice_total($current_invoice, $invoice_total);
$grand_total += $invoice_amount;
$current_invoice = $row['supplierinv'];
$invoice_total = 0;
}
$invoice_total += $row['amount'];
show_expense($row);
}
if ($current_invoice > 0) {
show_invoice_total($current_invoice, $invoice_total);
$grand_total += $invoice_amount;
}
show_grand_total($grand_total);
您可以让数据库对每张发票和总计进行汇总,如下所示:
select date, supplierinv, amount,
sum(amount) over(partition by supplierinv) as invoice_amount,
sum(amount) over()
from expenses
虽然您仍然需要进行一些后期处理才能明智地显示它,所以这并没有真正获得任何恕我直言。