[英]Adding the sum of two values in a query
所以我做了一个查询,得到以下结果
+---------------+---------------+---------+---------
| payID | payRate | hours | Earnings
+---------------+---------------+---------+--------
| entertainment| 12 | 18 | 216
| retail | 10 | 28 | 280
+---------------+---------------+---------+----------
查询和代码的其他部分如下:
$query = "SELECT jobId, payRate, SUM(hours) AS 'All_Hours' ,payRate * SUM(hours) AS 'total'
FROM users INNER JOIN deposit ON userId = empId
WHERE users.email = '" . $_SESSION['email'] ."'
GROUP BY jobId,payRate";
$result = mysqli_query($db, $query); //we make the query
if (!$result) { //if the query failed
echo("<p id = 'greatideadescription'>
Error, the query could not be executed: " .
mysqli_error($db) . "</p>");
mysqli_close($db);}
if (mysqli_num_rows($result) == 0) { //if no rows returned
echo("<tr><td />
<td>No Results</td>
<td /></tr>");
mysqli_close($db); //close the database
exit("</table></div></form></div></div>
<script>DisplayFooter();</script></body></html>");
}
$numRows = mysqli_num_rows($result); //gets number of rows
$numFields = mysqli_num_fields($result); //gets number of fields
//prints the data in the table
PrintTable($result, $numRows, $numFields);
函数PrintTable如下
function PrintTable($result, $numRows, $numFields) {
$row = mysqli_fetch_row($result); //fetches the first row
for ($i = 0; $i < $numRows; $i++) {
echo("<tr>"); //opens a new row
for ($j = 0; $j < $numFields; $j++) { //second loop goes through columns
echo("<td>" . $row[$j] . "</td>");
} //end inner for loop
$row = mysqli_fetch_row($result); //fetches subsequent rows
echo("</tr>"); //closes the row
} //end outer for loop
}
我想要的是回显收入的总和,在这种情况下,它将是496。我该怎么做?
如果您知道总和列的列索引,则可以尝试如下操作:
function PrintTable($result, $numRows, $numFields) {
$total = 0; // Initialize variable before going through each row
$row = mysqli_fetch_row($result); //fetches the first row
for ($i = 0; $i < $numRows; $i++) {
echo("<tr>"); //opens a new row
for ($j = 0; $j < $numFields; $j++) { //second loop goes through columns
echo("<td>" . $row[$j] . "</td>");
if($j == 3)
$total += $row[$j];
} //end inner for loop
$row = mysqli_fetch_row($result); //fetches subsequent rows
echo("</tr>"); //closes the row
} //end outer for loop
}
之后,您可以使用总计或将其返回到您的主代码中以在关闭表或或或之后回显它。
更好的方法是进行3个更改:
payRate * SUM(hours) AS earnings
在您的sql语句中,稍后您将使用该名称 mysqli_fetch_assoc
获取一个关联数组,您可以在其中按名称访问列( $row['earnings']
) 使用哪种方式取决于您...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.