您好,我有这样的表格信息:
我想在 php 中使用 while 或仅在 mysql 中对状态为 44 的行求和(time_used),直到到达状态为 55 的行。之后它应该从新的求和开始。
第一个查询应该返回 37,第二个查询应该返回 76(请记住它应该是通用的,对于 55 状态行的无限次出现)
我想到了一种时间/日期过滤的方法,并且有这个:
select sum(time_used) as sumed
from timelog
where start_time > (select end_time from timelog where (status='55')
ORDER BY id DESC LIMIT 1) ORDER BY id DESC
但这仅适用于 44 和 55 的最后组合
我知道我需要两种过滤方式(< end_time 和 > end_time)所以它适用于所有情况,但想不出在 php 中实现的方法
谁能帮帮我?
编辑: sqlfiddle 谁想要它:
最佳答案
有两种方法可以做到这一点:纯 SQL 或 PHP。如果您处理数千行,通过测试性能在两者之间进行选择可能会很有趣。
纯 SQL
select project_id, task_id, user_id, sum(time_used) as time_used, min(start_time) as start_time, max(end_time) as end_time, max(comment) as comment from (select t.id, t.project_id, t.task_id, t.user_id, t.time_used, count(t2.id) as count55, t.start_time, t.end_time, t.comment from timelog t left join timelog t2 on t.id>t2.id and t2.status=55 and t.task_id=t2.task_id group by t.id) as t group by count55;
我这里假设一个任务只能属于一个用户
SQL 和 PHP
$link = mysqli_connect( ... ); $query = "select id, project_id, task_id, user_id, time_used, start_time, end_time, status from timelog order by id"; $result = mysqli_query($link, $query); $table = array(); $time_used = 0; $start_sum = true; $i = 0; while($row = mysqli_fetch_assoc ($result)){ if($start_sum){ $table[$i] = $row; $start_sum = false; } else { $table[$i]['time_used'] += $row['time_used']; $table[$i]['end_time'] += $row['end_time']; } if($row['state'] == 55){ $i++; $start_sum = true; } }
如果可以同时运行两个任务,则解决方案 1 可行,但需要调整解决方案 2 以考虑到这一点。
关于php - 使用/不使用 php 在 MYSQL 中按日期求和和分隔的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18675404/