我正在尝试创建一个查询,该查询将在整个24小时工作日累计轮班员工人数。因此,当用户采取从2013-06-17 10:00:00开始到14:00:00结束的班次时,我希望用户在5个单元格中“计数”
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
这应该最终为我提供24小时范围,向我显示在特定时间内有多少员工在工作。
我使用了3张桌子。
teamslots
---------
id
startdate
starttime
endtime
teamslot_schedule
-----------------
id
slotid (joins to is in teamslots)
userid
shifthours
----------
thehour
在shifthours中,我有24条记录 - 0 - 23我需要的每小时一条记录。
然后我尝试在HOUR(teamslots.starttime)AND GROUP BY startdate上休息,小时但没有真正的运气。
这是我的查询(当前返回24行的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;
有谁能请我帮助我 - 指出我正确的方向?
答案 0 :(得分:0)
简短的想法。在相关日期提出一系列小时数(假设查询提前知道日期),并在开始和结束时间之间进行联接。
像这样: -
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)
请注意,这不会直接起作用,因为我不确定您的starttime / endtime与startdate的关系。
答案 1 :(得分: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