gpt4 book ai didi

PHP 在 while 循环中求和一个值,但有条件

转载 作者:搜寻专家 更新时间:2023-10-31 20:40:00 24 4
gpt4 key购买 nike

我有两个表要加入,1个是用户,1个是考勤。

TABLE : attendance
id userId totalHours
1 1 0745
2 3 0845
3 1 0945

TABLE : user
id name departmentId
1 John 2
2 Sean 2
3 Allan 2

不是每个用户都有出勤记录(他们的总小时数)但是我需要通过 userId WHERE departmentId = XXXX 和 SUM 他们存在的每个 totalHours 来查询,而不忽略没有任何出勤记录的 userId。

到目前为止我做了这个:

$result = mysqli_query($con,"SELECT * FROM user WHERE departmentId = 2");
while($row = mysqli_fetch_array($result))
{
$id = $row['userId'];
$result2 = mysqli_query($con,"SELECT * FROM attendance WHERE userId = $id");
while($row2 = mysqli_fetch_array($result2))
$totalHours = 0;
{
$totalHours = $row2['totalHours'];
$grandTotal += $totalHours;
$totalHoursInHHmm = substr_replace($totalHours,":",2,0);
$parsed = date_parse($totalHoursInHHmm);
$toSeconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60;
$total += $toSeconds;
$init = $total;
$hours = floor($init / 3600);
$minutes = floor(($init / 60) % 60);
}
echo "$hours:$minutes";
}

结果显示了部门内的所有用户,并对每个 userId 的所有 totalHours 进行了 SUM,但错误的是,没有任何出勤的 userId 仍然显示 SUM 值,继承了之前的总和

感谢任何帮助:)

最佳答案

I need to query by userId WHERE departmentId = XXXX and SUM each of their totalHours that exist, without neglecting the userId without any record in attendance.

要显示给定部门中所有用户的小时数,甚至是 attendance 表中没有行的用户,请使用 LEFT JOIN

使用 (CAST(totalHours AS UNSIGNED) % 100)/60 + FLOOR(CAST(totalHours AS UNSIGNED)/100) 将您的 varchar 小时+分钟转换为单个小时数。

$query = "SELECT u.id, 
SUM((CAST(totalHours AS UNSIGNED) % 100)/60 + FLOOR(CAST(totalHours AS UNSIGNED)/100)) grandTotal
FROM user u
LEFT JOIN attendance a
ON u.id = a.userId
WHERE u.departmentId = 2
GROUP BY u.id";

$result = mysqli_query($con,$query);

while($row = mysqli_fetch_array($result)) {
print $row['id'] . ' ' . $row['grandTotal'];
}

关于PHP 在 while 循环中求和一个值,但有条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24601898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com