1

I'm trying to create a query that will accrue the number of employees on shift, the entire 24 hours day. So when a user takes a shift that begin 2013-06-17 10:00:00 AND ends 14:00:00, I'd like the user to "count" in 5 cells

2013-06-17 10 : +1 here
2013-06-17 11 : +1 here
2013-06-17 12 : +1 here
2013-06-17 13 : +1 here
2013-06-17 14 : +1 here

This should end up providing me with a 24 hour range, showing me how many employees that are on job in the specific hour.

I have 3 tables that I use.

teamslots
---------
id
startdate
starttime
endtime

teamslot_schedule
-----------------
id
slotid (joins to is in teamslots)
userid

shifthours
----------
thehour

In shifthours I have 24 records - 0 - 23 one for each hour I need.

I then tried to LEFT JOIN on HOUR(teamslots.starttime) AND GROUP BY startdate,thehour but with no real luck.

Here's my query (that currently returns 24 rows of thehour,null,null)

SELECT a.thehour,b.startdate,b.taken FROM shifthours a LEFT JOIN (SELECT startdate,starttime,endtime,count(DISTINCT b.id) as taken FROM teamslots a
LEFT JOIN teamslot_schedule b ON a.id=b.slotid) b ON a.thehour=HOUR(b.starttime)
GROUP BY b.startdate,a.thehour;

Could anyone please help me out here - point me in the right direction ?

4

2 回答 2

0

以下查询将包括无人工作的几个小时的存储桶:

SELECT
    DATE_FORMAT(d.startdate + INTERVAL s.thehour HOUR, '%Y-%m-%d %H') AS date,
    COUNT(DISTINCT ts.userid) AS users
FROM
    shifthours s
JOIN
    (SELECT DISTINCT startdate FROM teamslots) d
LEFT JOIN
    teamslots t ON t.startdate = d.startdate AND
        s.thehour BETWEEN HOUR(t.starttime) AND HOUR(t.endtime)
LEFT JOIN
    teamslot_schedule ts ON ts.slotid = t.id
GROUP BY
    d.startdate,
    s.thehour
ORDER BY
    d.startdate + INTERVAL s.thehour HOUR;

有关工作示例,请参见http://sqlfiddle.com/#!2/4a716/13

以下查询将仅包含有人工作时的行:

SELECT
    DATE_FORMAT(t.startdate + INTERVAL s.thehour HOUR, '%Y-%m-%d %H') AS date,
    COUNT(DISTINCT ts.userid) AS users
FROM
    shifthours s
INNER JOIN
    teamslots t ON s.thehour BETWEEN HOUR(t.starttime) AND HOUR(t.endtime)
LEFT JOIN
    teamslot_schedule ts ON ts.slotid = t.id
GROUP BY
    t.startdate,
    s.thehour
ORDER BY
    t.startdate + INTERVAL s.thehour HOUR;

有关工作示例,请参见http://sqlfiddle.com/#!2/4a716/15

于 2013-06-17T16:52:26.367 回答
0

简短的想法。想出相关日期的时间范围(假设这一天是查询提前知道的)并在开始时间和结束时间之间进行 JOIN。

像这样:-

SELECT DATE_ADD('2013/06/17', INTERVAL thehour HOUR), COUNT(teamslot_schedule.id)
FROM shifthours
LEFT OUTER JOIN teamslots
ON DATE_ADD('2013/06/17', INTERVAL thehour HOUR) BETWEEN starttime AND starttime AND endtime
LEFT OUTER JOIN teamslot_schedule
ON teamslots.id = teamslot_schedule.slotid
GROUP BY DATE_ADD('2013/06/17', INTERVAL thehour HOUR)

请注意,这不会直接奏效,因为我不确定您的开始时间/结束时间与开始日期的关系。

于 2013-06-17T16:43:34.490 回答