我在mysql中有这个表
这是我的代码 //生成报告
<center>
<table border=1 cellpadding=10>
<tr>
<td rowspan="2">TANGGAL</td>
<td colspan="2" align="center">PAGI</td>
<td colspan="2" align="center">SORE</td>
<td rowspan="2">JML. JAM</td>
<td rowspan="2">JML. Rp</td>
</tr>
<tr>
<td>Masuk</td>
<td>Keluar</td>
<td>Masuk</td>
<td>Keluar</td>
</tr>
<?php
$qry_tgl=mysql_query("SELECT id_peg, date(waktu) Tgl from absen where id_peg=1 group by Tgl");
while($row=mysql_fetch_array($qry_tgl)){
echo "<tr>";
echo "<td>".$row['Tgl']."</td>";
echo "</tr>";
}
echo "</table></center>";
请帮助我,我很困惑该怎么做
三江源
答案 0 :(得分:1)
您的HTML代码似乎没问题,但SQL查询没有。我假设您在询问如何进行正确的查询。使用GROUP BY时,您应该(并且在默认情况下在较新的MySQL版本中)必须仅选择具有SUM,AVG等聚合函数的字段,或者选择GROUP BY中指定的字段。您无法按选择的结果进行分组。
您的查询应该是这样的:
SELECT DATE(waktu) Tgl FROM absen WHERE id_peg=1 GROUP BY DATE(waktu)
编辑:好的,根据谷歌翻译和其他网站Masuk / Keluar是自/直到。使用新提供的信息,这应该可以解决问题:
<center>
<table border=1 cellpadding=10>
<tr>
<td rowspan="2">TANGGAL</td>
<td colspan="2" align="center">PAGI</td>
<td colspan="2" align="center">SORE</td>
<td rowspan="2">JML. JAM</td>
<td rowspan="2">JML. Rp</td>
</tr>
<tr>
<td>Masuk</td>
<td>Keluar</td>
<td>Masuk</td>
<td>Keluar</td>
</tr>
<?php
function display_row($timeRanges) {
$pagi = isset($timeRanges[1]) ? strtotime($timeRanges[1]) - strtotime($timeRanges[0]) : 0;
$sore = isset($timeRanges[3]) ? strtotime($timeRanges[3]) - strtotime($timeRanges[2]) : 0;
$seconds = $pagi + $sore;
echo "<tr>";
echo "<td>" . substr($timeRanges[0], 0, 10) . "</td>"; // TANGGAL
echo "<td>" . substr($timeRanges[0], 11, 8) . "</td>"; // PAGI Masuk
echo "<td>" . (isset($timeRanges[1]) ? substr($timeRanges[1], 11, 8) : "") . "</td>"; // PAGI Keluar
echo "<td>" . (isset($timeRanges[2]) ? substr($timeRanges[2], 11, 8) : "") . "</td>"; // SORE Masuk
echo "<td>" . (isset($timeRanges[3]) ? substr($timeRanges[3], 11, 8) : "") . "</td>"; // SORE Keluar
echo "<td>" . round($seconds / 3600, 2) . "</td>"; // JML. JAM shows rounded number of hours
echo "<td>" . round($seconds * 5000 / 3600) . "</td>"; // JML. Rp number hours * 5000
echo "</tr>";
}
$qry_tgl=mysql_query("SELECT DATE(waktu) Tgl, waktu FROM absen WHERE id_peg=1 ORDER BY waktu");
$lastDate = null;
$timeRanges = array();
while($row=mysql_fetch_array($qry_tgl)){
if( $row['Tgl'] !== $lastDate ) {
if( $lastDate !== null )
display_row($timeRanges); // renders the row when the date changes, but only if we fetched at least one date
$lastDate = $row['Tgl'];
$timeRanges = array();
}
$timeRanges[] = $row["waktu"];
}
if( $lastDate !== null )
display_row($timeRanges); // renders the last row when the loop ends, but also only if we fetched at least one date
echo "</table></center>";
此算法将日期读入$timeRanges
数组,直到遇到另一个日期。因此,当调用display_row()
函数时,$timeRanges
将仅包含同一日期的有序记录。
我担心只使用MySQL会很慢并且浪费大量资源。