1

Hi i have such table information:

example

what i want to do with php with while or just in mysql, is to SUM (time_used) of the rows with status 44 until its reached row with status 55. after that it should begin from start with new summing.

first query should return 37, second 76 (keep in mind it should be universal, for unlimited occurrences of 55 status row)

i thought of a way with time/date filtering and have this:

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 

but this works only for last combination of 44 and 55

i know i will need two way filtering( < end_time and > end_time) so it will work for all cases, but cant think of a way to do it in php

can anyone help me?

EDIT: sqlfiddle whoever want it:

http://sqlfiddle.com/#!2/33820/2/0

4

3 回答 3

2

有两种方法可以做到这一点:纯 SQL 或 PHP。如果您处理数千行,通过测试性能在两者之间进行选择可能会很有趣。

  1. 纯 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;
    

    我在这里假设一项任务只能属于一个用户

  2. 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 需要进行调整才能考虑到这一点。

于 2013-09-07T18:04:39.480 回答
1

我既不是 php 也不是 MySQL 程序员,但我可以解释你想要遵循的逻辑。然后,您可以对其进行编码。

首先,查询您的数据库并将结果返回给 php。
接下来,将两个总和变量设置为 0。开始遍历查询结果。增加第一个 sum 变量,直到到达状态为 55 的第一行。完成后,开始增加第二个变量。

棘手的部分是按表的行号对查询进行排序。 这是一个链接,可以帮助您完成该部分。

于 2013-09-07T16:56:46.940 回答
1

这是我的解释:http://sqlfiddle.com/#! 2/33820/45

  set @n=0;
    select project_id, task_id, user_id,sum(time_used)  from (
    SELECT  time_used,project_id, task_id, user_id,
            @n:=if(status=55,@n+1,@n),
            if(status=55,-1,@n) as grouper FROM timelog
    ) as t
    where grouper>-1
    group by grouper;
于 2013-09-07T18:51:52.083 回答