我很难弄清楚代码中的问题所在。我有一些工作在不同频率周期性地运行。从这些工作中,我需要数据来获取作业表中所有独特工作的最新作业运行数据。
任何帮助都将受到高度赞赏。
工作 - 主表
Job_Id Name
1 Job1
2 Job2
3 Job3
乔布斯历史
Id Job_Id StartTime EndTime
100 1 2015-03-11 16:03:49.760 2015-03-11 16:09:49.760
101 2 2015-03-10 16:03:49.760 2015-03-10 16:40:49.760
102 3 2015-02-11 16:03:49.760 2015-02-11 16:09:49.760
103 2 2015-03-11 16:03:49.760 2015-03-11 16:09:49.760
104 1 2015-03-11 16:08:49.760 2015-03-11 16:12:49.760
105 1 2015-03-11 16:12:49.760 2015-03-11 16:16:49.760
106 1 2015-03-11 16:20:49.760 2015-03-11 16:29:49.760
输出:我需要下面的内容。每个作业的最新作业数据。每个工作频率都不一样。
Id Name StartTime EndTime
106 Job1 2015-03-11 16:20:49.760 2015-03-11 16:29:49.760
103 Job2 2015-03-11 16:03:49.760 2015-03-11 16:09:49.760
102 Job3 2015-02-11 16:03:49.760 2015-02-11 16:09:49.760
SELECT top 1* FROM Jobs j
INNER JOIN JobsHistory jh ON j.Id = jh.Job_Id
where jh.Job_Id in (select Id from Jobs )
order by jh.starttime desc
答案 0 :(得分:2)
尝试这样的事情
带有ROW_NUMBER()
子句的OVER()
将为您的作业编号,按StartTime(降序)排序,并为每个Job_Id分区编号。具有数字1的所有行应该是每个Job_Id
SELECT *
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY Job_Id ORDER BY StartTime DESC) AS OrderNr
,*
FROM Jobs j
INNER JOIN JobsHistory jh ON j.Id = jh.Job_Id
) AS tbl
WHERE tbl.OrderNr=1
答案 1 :(得分:0)
Shnugo提供的答案工作正常,但速度很慢。我找到了另一种使用CTE查询的方法,它更快(<1秒)。只想分享查询以帮助他人。
WITH JH_CTE(Id, RecentRunId) AS (SELECT Job_Id, max(Id) FROM JobsHistory GROUP BY Job_Id)
SELECT * from Jobs j
JOIN JH_CTE on j.Job_Id = JH_CTE.Id
JOIN JobsHistory jh on jh.Id = JH_CTE.RecentRunId