[英]rank query in sql server 2000
I am trying to create a query that will bring the last STATUS of a JOB_ID, this would be simple in SQL Server 2008 using the rank over partition function, but on SQL Server 2000 this function is not available. 我正在尝试创建一个查询,该查询将带来一个JOB_ID的最后状态,这在SQL Server 2008中使用基于分区的排名功能很简单,但是在SQL Server 2000上,此功能不可用。 I have managed to put the job history in order by Job_ID ascending and DATETIME descening in a temporary table ( #JOB_HISTORY -note that the pk_ID is generated in the temporary table using:
IDENTITY(int, 1,1)
), but here is the part where I got stuck, I dont know how to rank the records in this table. 我已经设法通过Job_ID升序和DATETIME降序将作业历史记录按顺序放在临时表中( # JOB_HISTORY-请注意pk_ID是使用以下临时表生成的:
IDENTITY(int, 1,1)
),但这是我卡住的部分,我不知道如何对这张表中的记录进行排名。
SELECT
h1.pk_ID,
h1.Job_ID,
h1.Status,
h1.DATETIME
FROM #JOB_HISTORY h1
ORDER BY h1.pk_ID ASC;
#JOB_HISTORY RESULT: #JOB_HISTORY结果:
pk_ID, Job_ID, STATUS, DATETIME
1 1234 Succeded. 2015-03-30 12:10
2 1234 Failed. 2015-03-30 01:00
3 1234 Failed. 2015-03-28 01:00
4 5678 Failed. 2015-04-02 04:00
5 5678 Succeded. 2015-04-01 04:00
6 5678 Succeded. 2015-03-31 04:00
DESIRED OUTPUT: 期望的输出:
Job_ID STATUS DATETIME
1234 Succeded. 2015-03-30 12:10
5678 Failed. 2015-04-02 04:00
SQL Server has freedom to insert records in any order it wants, so I wouldn't trust IDENTITY(int, 1,1)
to always give you the right sequence. SQL Server可以按任意顺序自由插入记录,因此我不相信
IDENTITY(int, 1,1)
总是为您提供正确的顺序。 It may work in some versions though. 它可能在某些版本中有效。
You could inner join a sub query where you get the max datetime (or min pk_ID) to get the first/last rows. 您可以在内部加入一个子查询,在其中获得最大日期时间(或最小pk_ID)以获取第一行/最后一行。 Here's a working example for getting the last outcome of each job in SQL Server 2000:
这是一个获得SQL Server 2000中每个作业的最后结果的工作示例:
use msdb;
select
sysjobhistory.job_id as job_id
-- https://msdn.microsoft.com/en-us/library/ms174997.aspx
, case sysjobhistory.run_status
when 0 then 'Failed'
when 1 then 'Succeeded'
when 2 then 'Retry'
when 3 then 'Canceled'
else cast(sysjobhistory.run_status as varchar(10))
end as run_status
, jobLastHistory.lastDateTime as execution_time
FROM dbo.sysjobhistory as sysjobhistory
inner join (
--last datetime for each job_id
SELECT
history.job_id
, max( --newest
CONVERT(DATETIME, STUFF(STUFF(STUFF( --yyyymmddhhmiss --> datetime
cast(history.run_date as varchar(8))--yyyymmdd
+right('000000'+cast(history.run_time as varchar(8)),6) --hhmiss
,13,0,':'),11,0,':'),9,0,' '))
) AS lastDateTime
FROM dbo.sysjobhistory as history
where history.step_id = 0 --job outcome
group by
history.job_id
) as jobLastHistory
on jobLastHistory.job_id
= sysjobhistory.job_id --same job
and convert(varchar(8),jobLastHistory.lastDateTime,112)
= sysjobhistory.run_date --latest date (yyyymmdd)
and replace(convert(varchar(8),jobLastHistory.lastDateTime,108),':','')
= sysjobhistory.run_time --latest time (hhmiss)
where sysjobhistory.step_id = 0 --job outcome
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.