我有一张名为费用的表格。有很多列,但我的php页面中涉及的是日期,spplierinv,金额。我创建了一个页面,列出了给定月份中的所有费用,并在最后总计。但是,每一行都有一个值,但许多行可能位于同一供应商发票上。这意味着每行添加相同的supplierinv以获得根据我的银行对帐单的总额。无论如何,我可以根据supplierinv得到行的总数。我的意思是说我有10行。在supplierinv 4上有5个,在supplierinv 5上有2个,在supplierinv 12上有3个,如何获得3个数字(inv 4,5和12)以及底部的总数。非常感谢
答案 0 :(得分:1)
您是否需要显示各个费用行以及所有总计?如果没有,您可以按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'];
}
另一种方法,如果要显示分成发票的表格,只需确保结果按supplierinv排序,然后:
$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
虽然你仍然需要进行一些后期处理来合理地显示,但这并没有真正获得任何东西。