每个员工都已经在AvailSlots中有一个可用时间表,如下所示:
Staff_ID Avail_Slots_Datetime
1 2015-1-1 09:00:00
1 2015-1-1 10:00:00
1 2015-1-1 11:00:00
2 2015-1-1 09:00:00
2 2015-1-1 10:00:00
2 2015-1-1 11:00:00
3 2015-1-1 09:00:00
3 2015-1-1 12:00:00
3 2015-1-1 15:00:00
我需要找出哪些员工在每个时段都有2个(或3,4个等)CONSECUTIVE可用时间段。作为一个新手,如果查询是连续2个时隙,下面的INNER JOIN代码就是我所知道的。
SELECT a.start_time, a.person
FROM a_free a, a_free b
WHERE (b.start_time = addtime( a.start_time, '01:00:00' )) and (a.person = b.person)
但是,显然,这样做,我将不得不为每种情况添加更多INNER JOIN代码 - 取决于查询是针对3,或4还是5等在给定日期的连续可用时间段/小时。因此,我想学习一种更有效,更灵活的方法来做同样的事情。具体来说,我需要的查询代码(用自然语言)是这样的:
对于AvailSlots中的每个时段,列出一个有X的人员(X可以在哪里) 是我为每个查询指定的任何数字,从1到24)连续的日期时间 从该日期时间开始的插槽。如果有多名员工可以见面 这个标准,抢七局是他们的排名"保存在一个 单独的表格:
Ranking Table (lower number = higher rank)
Staff_ID Rank
1 3
2 1
3 2
如果答案是使用" mysql变量"," views"等等,请详细解释这些事情是如何工作的。再次,作为一个总的mysql新手,"选择","加入","其中","分组"到目前为止我都知道。我渴望了解更多,但到目前为止无法理解更高级的mysql概念。非常感谢提前。
答案 0 :(得分:1)
使用比您发布的数据更多的数据,我发现了一个可能满足您需求的查询。它确实使用你预测的变量:)但我希望它非常明显。让我们从表格开始:
CREATE TABLE a_free
(`Staff_ID` int, `Avail_Slots_Datetime` datetime)
;
INSERT INTO a_free
(`Staff_ID`, `Avail_Slots_Datetime`)
VALUES
(1, '2015-01-01 09:00:00'),
(1, '2015-01-01 10:00:00'),
(1, '2015-01-01 11:00:00'),
(1, '2015-01-01 13:00:00'),
(2, '2015-01-01 09:00:00'),
(2, '2015-01-01 10:00:00'),
(2, '2015-01-01 11:00:00'),
(3, '2015-01-01 09:00:00'),
(3, '2015-01-01 12:00:00'),
(3, '2015-01-01 15:00:00'),
(3, '2015-01-01 16:00:00'),
(3, '2015-01-01 17:00:00'),
(3, '2015-01-01 18:00:00')
;
然后查询连续的插槽。它列出了每对的开始时间,并用唯一的数字标记每组连续的插槽。案例表达是魔术发生的地方,见评论:
select
Staff_ID,
Avail_Slots_Datetime as slot_start,
case
when @slot_group is null then @slot_group:=0 -- initalize the variable
when @prev_end <> Avail_Slots_Datetime then @slot_group:=@slot_group+1 -- iterate if previous slot end does not match current one's start
else @slot_group -- otherwise just just keep the value
end as slot_group,
@prev_end:= Avail_Slots_Datetime + interval 1 hour as slot_end -- store the current slot end to compare with next row
from a_free
order by Staff_ID, Avail_Slots_Datetime asc;
如果列表中标识了插槽组,我们可以将上面的查询包装在另一个中,以获得每个插槽组的长度。第一个查询的结果被视为任何其他表:
select
Staff_ID,
slot_group,
min(slot_start) as group_start,
max(slot_end) as group_end,
count(*) as group_length
from (
select
Staff_ID,
Avail_Slots_Datetime as slot_start,
case
when @slot_group is null then @slot_group:=0
when @prev_end <> Avail_Slots_Datetime then @slot_group:=@slot_group+1
else @slot_group
end as slot_group,
@prev_end:= Avail_Slots_Datetime + interval 1 hour as slot_end
from a_free
order by Staff_ID, Avail_Slots_Datetime asc
) groups
group by Staff_ID, slot_group;
注意:如果使用相同的数据库连接再次执行查询,则不会重置变量,因此slot_groups编号将继续增长。这通常不应该是一个问题,但为了安全起见,你需要在之前或之后执行这样的事情:
select @prev_end:=null;
如果您愿意,请与小提琴一起玩:http://sqlfiddle.com/#!2/0446c8/15