SQL Last DateTime值

问题描述 投票:0回答:1

我正在尝试查询一些“作业”数据库,其中我需要给定作业中每个operation_service的最后一个日期时间值。我还需要知道操作是否完成。

SELECT Job.Job, Job_Operation.Operation_Service, Job_Operation.Sequence, 
MAX(Job_Operation_Time.Last_Updated) AS 'Last_Updated', Job_Operation_Time.Operation_Complete
FROM  Job_Operation 
LEFT JOIN Job ON Job.Job = Job_Operation.Job 
LEFT JOIN Job_Operation_Time ON Job_Operation_Time.Job_Operation = Job_Operation.Job_Operation
WHERE Job.Status = 'Active'
GROUP BY Job.Job, Job_Operation.Operation_Service, Job_Operation.Sequence, Job_Operation_Time.Last_Updated, Job_Operation_Time.Operation_Complete
ORDER BY Job.Job, Sequence

这里有一些结果片段:

enter image description here

我想要的是一个返回所有突出显示的记录但不返回通过作业字段用红线记录的查询。 Operation_Complete和Last_Updated都可以使用NULL值。

sql datetime ssms
1个回答
0
投票

使用row_number()

with cte  as
(
SELECT Job.Job, Job_Operation.Operation_Service, Job_Operation.Sequence, 
(Job_Operation_Time.Last_Updated) AS 'Last_Updated', Job_Operation_Time.Operation_Complete
,row_number()over(partition by Job_Operation.Operation_Service order by Job_Operation_Time.Last_Updated desc) rn
FROM  Job_Operation 
LEFT JOIN Job ON Job.Job = Job_Operation.Job 
LEFT JOIN Job_Operation_Time ON Job_Operation_Time.Job_Operation = Job_Operation.Job_Operation
WHERE Job.Status = 'Active'
) select * from cte where rn=1
© www.soinside.com 2019 - 2024. All rights reserved.