我有一个表,其中包含以下示例之类的任务:
id user_id project_id done_at duration type
1 13 15 2014-08-11 03:00:00 1
2 13 15 2014-08-11 04:00:00 1
10 13 15 2014-08-12 04:00:00 1
3 13 15 2014-08-12 08:00:00 2
5 13 13 2014-08-13 08:00:00 1
7 13 15 2014-08-14 04:00:00 1
8 13 15 2014-08-18 08:00:00 1
9 13 15 2014-08-19 08:00:00 2
如何按用户,项目和类型获取连续done_at列的开始/结束序列,如下所示:
user_id project_id type start_done_at end_done_at duration
13 15 1 2014-08-11 2014-08-12 11:00:00
13 15 2 2014-08-12 2014-08-12 08:00:00
13 13 1 2014-08-13 2014-08-14 12:00:00
13 15 1 2014-08-18 2014-08-18 08:00:00
13 15 2 2014-08-19 2014-08-19 08:00:00
我已经尝试过以下示例:http://www.artfulsoftware.com/infotree/qrytip.php?id=76但是我没有做正确的持续时间。
我目前的疑问是:
SELECT task.user_id as user_id, task.done_at as start_done_at, MIN(task2.done_at) as end_done_at, task.project_id as project_id, task.timeoff_type_id as timeoff_type, SEC_TO_TIME(SUM(TIME_TO_SEC(task.duration))) as duration
FROM tasks task
LEFT JOIN tasks task1 ON task.done_at = task1.done_at + 1
AND task.user_id = task1.user_id
AND task.project_id = task1.project_id
AND task.timeoff_type_id = task1.timeoff_type_id
LEFT JOIN tasks task2 ON task.done_at <= task2.done_at
AND task.user_id = task2.user_id
AND task.project_id = task2.project_id
AND task.timeoff_type_id = task2.timeoff_type_id
LEFT JOIN tasks task3 ON task2.done_at = task3.done_at -1
AND task2.user_id = task3.user_id
AND task2.project_id = task3.project_id
AND task2.timeoff_type_id = task3.timeoff_type_id
WHERE task1.done_at IS NULL
AND task2.done_at IS NOT NULL
AND task3.done_at IS NULL
GROUP BY task.user_id, task.project_id, task.timeoff_type_id, task.done_at
答案 0 :(得分:1)
select
user_id, project_id,
min(done_at) as start_done_at,
max(done_at) as end_done_at,
sec_to_time(sum(time_to_sec(duration))) as duration
from (
select
t.*,
@gn := if(timestampdiff(day, @prev_date, done_at) between 0 and 1 and @prev_type = type and @prev_project = project_id, @gn, @gn + 1) as group_number,
@prev_date := done_at,
@prev_type := type,
@prev_project := project_id
from
t
, (select @prev_project := null, @prev_date := null, @prev_type := null, @gn := 0) var_init
order by project_id, done_at, duration
) sq
group by group_number