如何将一个列/表中的多个日期的逻辑应用于另一列/表中的多个日期?

时间:2018-05-10 18:38:04

标签: mysql sql

我试图从每个“暂停”之前的最后一份工作中获取job_id。步骤

工作表

select job_id, stopped 
 from Job j 
 where j.task_id = 100

job_id      stopped
1451200     9/25/2014 14:57
1451201     10/1/2014 21:06
1451202     10/8/2014 13:45
1451203     10/14/2014 14:07
1451204     10/22/2014 14:47
1451205     10/29/2014 21:26
1451206     11/5/2014 14:41
1451207     11/18/2014 17:04
2074993     5/22/2015 15:47
2111136     5/28/2015 15:53
2111137     6/5/2015 14:17
2111138     6/11/2015 14:57
2111139     6/20/2015 14:55
2111140     6/27/2015 15:22
2111141     7/3/2015 15:34
2111142     7/9/2015 14:21
10605814    12/29/2017 22:44
10605815    1/26/2018 19:53

WorkFlowHistory表

select wfh_id, dateChange, step 
  from WorkFlowHistory wfh 
  where wfh.step like '%SUSP%' 
    and wfh.task_id = 100

wfh_id   dateChange         step
1628944  11/20/2014 22:04   SUSPENDED
1852694  5/19/2015 14:05    UNSUSPENDED
1861786  5/22/2015 13:24    SUSPENDED
1867582  5/25/2015 14:17    UNSUSPENDED
2006627  7/14/2015 13:24    SUSPENDED
2786512  3/24/2016 17:52    UNSUSPENDED
2811994  4/1/2016 20:02     SUSPENDED
6382968  12/28/2017 17:19   UNSUSPENDED
6537905  2/5/2018 16:57     SUSPENDED

我考虑这样做的逻辑是'声明。我的代码看起来像这样。

select
 case when stopped >= DT_CHG - interval 7 day 
      and stopped < DT_CHG 
      then job_id 
 end as susp_job_id
from Job j
join (select dateChange DT_CHG, task_id
       from WorkFlowHistory
       where step = 'SUSPENDED')wfh on wfh.task_id = j.task_id
where wfh.task_id = 100

我理想的结果集看起来像这样

id      stopped     wfh_id  dateChange  step
1451207 11/18/2014  1628944 11/20/2014  SUSPENDED
2074993 5/22/2015   1861786 5/22/2015   SUSPENDED
2111142 7/9/2015    2006627 7/14/2015   SUSPENDED

因为这三个job_id符合在暂停步骤dateChange之前一周内的标准。

然而,当我运行它时,它似乎只是根据最早的dateChange计算停止的日期,所以只返回结果。

id      stopped     wfh_id  dateChange  step
1451207 11/18/2014  1628944 11/20/2014  SUSPENDED

如何才能让这个逻辑正常工作,以便根据每个dateChange而不是最新的dateChange进行计算?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

这应该会产生您想要的结果,但我并不积极,因为您没有在示例数据中包含架构或所有相关数据的示例。它应该更快,因为它使用连接而不是子查询。

SELECT
    b.id,
    b.stopped,
    a.wfh_id,
    a.dateChange,
    a.step
FROM WorkFlowHistory a
JOIN Job b
ON a.task_id = b.task_id
    AND b.stopped BETWEEN a.dateChange - interval 7 day AND a.dateChange - interval 1 day
WHERE a.step = 'SUSPENDED'