如何将员工分组到几小时?

时间:2013-12-02 08:13:36

标签: mysql sql database select group-by

我有这张桌子可以节省员工执行日常任务的时间。

CREATE TABLE tasks (
   id INT NOT NULL PRIMARY KEY,
   name VARCHAR(100),
   date_task date,
   time_ini time,
   time_end time
);
  • 我正在尝试对至少有两个time_ini的员工进行分组<任何员工的time_ini或time_end都需要15分钟。
  • 如果他们的time_inis都没有达到这个条件,那么这名员工将被单独分组。
  • 这些组的编号从1到n。
  • 然后这些组将按日期升序排序,time_ini升序。

这是数据的一个例子:

(1,  "oscar", '2012-01-01', '01:30', '01:32'),
(2,  "oscar", '2012-01-01', '02:30', '02:32'),
(3,  "oscar", '2012-01-01', '05:30', '05:32'),
(4,  "oscar", '2012-01-01', '06:30', '06:32'),

(5,  "mario", '2012-01-01', '02:43', '02:43'),
(6,  "mario", '2012-01-01', '02:53', '02:53'),
(7,  "mario", '2012-01-01', '05:30', '05:30'),

(8, "martah", '2012-01-01', '01:25', '01:28'),
(9, "martah", '2012-01-01', '02:29', '02:41'),

(10, "jesus", '2012-01-01', '01:25', '01:28'),
(11, "jesus", '2012-01-01', '01:25', '02:28'),
(12, "jesus", '2012-01-01', '07:33', '08:32'),
(13, "jesus", '2012-01-01', '07:35', '07:36'),
(14, "jesus", '2012-01-01', '08:36', '08:39'),

(15, "rober", '2012-01-01', '02:43', '02:46'),
(16, "rober", '2012-01-01', '02:56', '03:00'),
(17, "rober", '2012-01-01', '02:29', '11:32'),

(18, "pedro", '2012-01-01', '11:36', '12:46'),
(19, "pedro", '2012-01-01', '12:36', '16:46');

这将是结果:

GROUP       NAME
1           oscar
1           marta
1           jesus
2           mario     
2           rober
3           pedro

我想出了类似的东西:

select distinct a.name 
from tasks a
where 
    (select count(id) 
    from tasks b 
    where (
          MINUTE(TIMEDIFF(a.time_ini, b.time_ini)) < 15 OR 
          MINUTE(TIMEDIFF(a.time_end, b.time_ini)) < 15
     ) and
    b.name <> a.name) >= 2;

我担心我不能用这种方式对它们进行分组,但我认为我的解决方案并不太远,不是吗?

任何想法,提示或建议将不胜感激,如果您需要更多信息,请告诉我,我将编辑帖子。有点难以解释......

1 个答案:

答案 0 :(得分:1)

你可以尝试这个(虽然它不是你需要它的格式......它应该做的工作):

SELECT
    a.id as groupId,
    a.name as first,
    b.name as second,
    COUNT(*) as occ
FROM 
    tasks a,task b
WHERE
    b.name <> a.name
    AND a.id > b.id
    AND (
        MINUTE(TIMEDIFF(a.date_ini, b.date_ini)) < 15 OR 
        MINUTE(TIMEDIFF(a.date_end, b.date_ini)) < 15
    )
GROUP BY
    groupId,
    first,
    second
由于记录10和11,

BTW jesus应该在oscarmartha的群组中