PHP实现符合服务协议日期范围且未关闭的Casenotes工时求和
问题原因
现有代码未添加Casenotes日期落在服务协议有效期内的过滤条件,且sa_closed = -0属于笔误,导致统计范围超出预期。
修正后的代码
<?php $sqltot = "SELECT SUM(Casenotes.cn_hours) AS total_hours FROM Casenotes INNER JOIN Service_Agreements ON Casenotes.part_id = Service_Agreements.participant_id AND Casenotes.serv_group = Service_Agreements.serv_group AND Casenotes.cn_group = Service_Agreements.cn_group WHERE Casenotes.part_id = :partid AND Casenotes.serv_group = :groupid AND Casenotes.cn_group = :cngroupid AND Service_Agreements.sa_closed = 0 -- 新增日期区间过滤,如Casenotes日期字段名不是cn_date请自行替换 AND Casenotes.cn_date BETWEEN Service_Agreements.sa_start_date AND Service_Agreements.sa_end_date"; $st = $pdo->prepare($sqltot); $st->bindvalue(':partid', $partid); $st->bindvalue(':groupid', $grp['serv_group']); $st->bindvalue(':cngroupid', $cngroupid); $st->execute(); foreach($st as $rowst) { echo $rowst['total_hours'] ?? 0; // 加??0避免无匹配数据时输出空 } ?>
修改说明
- 改用显式
INNER JOIN关联两张表,逻辑更清晰,避免隐式连接容易出现的多余匹配问题 - 新增日期区间判断条件,仅统计服务协议有效期内的Casenotes记录
- 修正
sa_closed = -0的错误为sa_closed = 0 - 输出时新增空值判断,无符合条件的数据时会输出0而不是空白
- 原有绑定参数不需要调整,没有新增传参
内容的提问来源于stack exchange,提问作者CoachPanda
相关产品推荐
相关产品推荐

