我正在尝试进行一个查询,该查询从一行获取'创建时间戳,然后根据第一个时间戳,根据INTERVAL中的'修改'时间戳计算唯一用户的数量。我得到一个输出,但它不是我所期望的。
我有一种感觉,我想要做的事情是不可能的,因为GROUP BY或DATE_SUB。这是我所拥有的骨架:
SELECT jobid, ctime, date, foo.count
FROM Table foo
JOIN (
SELECT
COUNT(DISTINCT user) AS count
FROM Table
WHERE mtime >= DATE_SUB(ctime, INTERVAL 12 HOUR)
GROUP BY window
) bar ON foo.id = bar.id
ORDER BY ctime
此查询的目的是,对于作业A,我可以查看作业A的创建时间,并根据有多少“已修改”计算过去12小时内有多少用户(工作人员)处于活动状态那段时间内的其他工作。
所以基本上,用这样的表:
jobid userid ctime mtime date
1 Alan 9:00 AM 11:00 AM 1st
2 Bob 10:00 AM 1:00 PM 1st
3 Carla 1:00 PM 11:00 PM 2nd
4 Dave 9:00 AM 10:00 AM 3rd
5 Emma 11:00 AM 1:00 PM 3rd
我想要的输出是这样的:
jobid ctime date foo.count
2 10:00 AM 1st 1
3 1:00 PM 2nd 0
4 9:00 AM 3rd 1
5 10:00 AM 3rd 2
我的查询是否在正确的轨道上?或者我是不是很开心?
编辑:
SELECT
ci.ctime AS "Job Creation Time",
ci.job_id AS "Job ID",
ci.pickup_time AS "Pickup Time",
HOUR(wt.ctime) AS "Active Window",
xx.Active AS "#Active in Window"
FROM worker_to AS wt
JOIN stats_ci_data ci ON ci.job_id = wt.id
JOIN `order` o ON o.id = wt.order_id
JOIN (
SELECT
wt.id AS `id`, wt.ctime,
DATE(wt.ctime) AS `date`,
DATE_FORMAT(wt.ctime, '%m-%d-%H') AS win,
COUNT(DISTINCT wt.worker_id) AS "Active"
FROM worker_to wt
JOIN `order` o ON o.id = wt.order_id
WHERE wt.mtime BETWEEN DATE_SUB(wt.ctime, INTERVAL 12 HOUR) AND wt.ctime
AND wt.tier != "machine"
AND wt.preferred_worker_flag != '1'
AND o.source LIKE '%Mozilla%'
OR o.source LIKE 'Opera%'
OR o.source LIKE 'Firefox%'
GROUP BY win
) xx ON xx.id = wt.id
WHERE wt.tier != "machine"
AND wt.preferred_worker_flag != "1"
AND o.source LIKE '%Mozilla%'
OR o.source LIKE 'Opera%'
OR o.source LIKE 'Firefox%'
ORDER BY ci.ctime, HOUR(wt.mtime)
;
所以,我使用了join而不是从同一个表中拉两次因为我需要放入一堆'过滤器',比如tier,preferred_worker,source。我认为这些正在减慢查询速度。但与此同时,我觉得时间间隔也没有给我正确的数字。目前,子查询按DATE
窗口分组,但活跃工人的数量每天为1,2,3,这似乎很低。
答案 0 :(得分:0)
我不太确定我完全理解你的问题,但我相信你想要这样的东西。 ctime
和mtime
是否包含日期和时间?如果没有,您将需要在下面的SQL中将它们替换为具有日期和时间的表达式。但这至少应该让你开始。
select this.jobid, this.ctime, this.date, count(*)
from Table this, Table other
where other.mtime between ( this.ctime - interval 12 hours ) and this.ctime
and this.userid != other.userid
group by this.jobid, this.ctime, this.date