获取每项工作的最后过程并确定状态

时间:2017-08-07 03:24:44

标签: mysql sql

如何获取某个作业的最后一步并确定每个作业的最后一个进程的状态是否等于1.如果最后一个进程的状态等于1,则显示该值。

JOB TABLE(prepressjobs)

+-----------+--------------+------------+
|    ID     | SchedNum     |  Item Name | 
+-----------+--------------+------------+
| 1         | JITE7ERUK    | Item 1     | 
| 2         | JV7FSW26Y    | Item 2     | 
| 3         | JQFXV4H3X    | Item 3     | 
+-----------+--------------+------------+

操作表(操作)

+-----------+--------------+------------+-----------+----------+
|    ID     | SchedNum     |  Job Name  |   Step    |  Status  |
+-----------+--------------+------------+-----------+----------+
| 1         | JITE7ERUK    | Designing  | 0         | 1        |
| 2         | JITE7ERUK    | Sample     | 1         | 1        |
| 3         | JITE7ERUK    | Printing   | 2         | 0        |
| 4         | JV7FSW26Y    | Designing  | 0         | 1        |
| 5         | JV7FSW26Y    | Sample     | 1         | 0        |
| 6         | JQFXV4H3X    | Designing  | 0         | 1        |
| 7         | JQFXV4H3X    | Sample     | 1         | 1        |
+-----------+--------------+------------+-----------+----------+

我的查询

SELECT *
FROM operation p1
INNER JOIN prepressjobs 
ON prepressjobs.pj_schednum = p1.operation_schednum 
WHERE EXISTS(SELECT MAX(operation_step) FROM (SELECT DISTINCT(operation_schednum) FROM operation )p2)
AND p1.operation_status = 0 ;

预期结果

+-----------+--------------+------------+-----------+----------+
| 7         | JQFXV4H3X    | Sample     | 1         | 1        |
+-----------+--------------+------------+-----------+----------+

2 个答案:

答案 0 :(得分:0)

尝试以下内容。这适用于SQL Server

 select * from 
 (
 select *,row_number() over(partition by schednum order by step desc ) as rn 
 from operations 
 ) a 
 where a.rn=1 and a.status=1;

答案 1 :(得分:0)

最后我自己拿到了它。但仍然感谢@Aparna的回应。另外,我在Retrieving the last record in each groupJOIN three tables有了一个想法。

QUERY:

SELECT * FROM operation t1
INNER JOIN prepressjobs 
ON prepressjobs.pj_schednum = t1.operation_schednum 
WHERE EXISTS(SELECT * FROM operation p2 WHERE p2.operation_step =   IF((t1.operation_step - 1)=-1,0,(t1.operation_step - 1) ) AND p2.operation_status = 1)
AND t1.operation_processname ='SINGLE DIELINE'
AND t1.operation_status = 0
AND prepressjobs.pj_status ='APPROVED'