有两种方法可以做到这一点。
PHP
保持所有“支付”值的总和,并将其添加到底部的表格中。例如:
$i=0;
while ($list = mysql_fetch_assoc($query)) { // for each row in your results
if ($id != $list['EmployeeId']) { // We only enter this loop if the EmployeeId doesn't equal $id. This can happen because either $id doesn't exist yet, or it doesn't match the previous EmployeeId
$i++; // increase $i by 1
if($i>1) { // Enter this loop only if $i is greater than or equal to 2 (if it is less than two, then this is our first time running this script, and adding a footer row wouldn't make any sense).
create footer (EmployeeId, Hours, Pay); // Log Id is irrelevant here
}
// reset your variables here
$id = $list['EmployeeId']; // set $id = the first or the new Employee ID
$total_pay = $list['pay']; // This is our first time for this Employee, so don't just add it to the running total
create header (EmployeeId, Hours, Pay) // Create the top half of your table
} else { // The EmployeeId has been established: we only need to change the running total
$total_pay = $total_pay + $list['pay'];
}
// add a data row for each LogId. This executes every time we go through the loop
create_normal_row(LogId, EmployeeId, Hours, Pay)
}
// At this point, both Employees have a header, and all data rows. However, we left the loop before we could add the last Employee's footer row
// Let's add one more footer row for the last user
create_footer (Logid, Hours, Pay);
SQL
MySQL 有一个功能与您正在尝试做的事情非常相似,称为ROLLUP
. 你可以在这里读更多关于它的内容:
http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html
基本上,您可以将查询更改为这样工作:
SELECT LogId, EmployeeId, SUM(Hours), SUM(Pay) FROM `log`
GROUP BY empid, logid WITH ROLLUP
此查询将返回如下所示的数据集:
---------------------------------------
| Logid | EmployeeId| Hours | Pay |
---------------------------------------
| 1001 | 1 | 10 | 50 |
---------------------------------------
| 1002 | 1 | 2 | 10 |
---------------------------------------
| NULL | 1 | 12 | 60 |
---------------------------------------
| 1003 | 2 | 3 | 9 |
---------------------------------------
| 1004 | 2 | 6 | 18 |
---------------------------------------
| NULL | 2 | 9 | 27 |
---------------------------------------
| NULL | NULL | 21 | 87 |
---------------------------------------
无论何时$list['Logid']
为空,您都知道您有一个“总计”行。不过要小心,这将在数据集的底部添加“所有员工的总和”行。如果$list['EmployeeId']
为空,那么您知道您在此“总计”行中。
在相关说明中(我不确定这是否是您所要求的),您可以使用 HTML<table>
元素在表格中显示这些内容。
每行看起来像这样:
<table> <!-- shown at the beginning of each table -->
<tr> <!-- shown at the beginning of each row -->
<td> <!-- shown at the beginning of each table cell -->
Your text goes here
</td> <!-- shown at the end of each table cell -->
<td>
More text can go here
</td>
</tr> <!-- shown at the end of each row -->
</table> <!-- shown at the end of each table -->
<tr>
s 可以在每个<table>
中无限重复,<td>
s 可以在<tr>
s 中重复。