在sql server 2000中排名查询

时间:2015-04-02 15:12:21

标签: sql sql-server database sql-server-2000 ranking

我正在尝试创建一个将带来JOB_ID的最后一个STATUS的查询,这在SQL Server 2008中使用rank over partition函数很简单,但在SQL Server 2000上这个函数不可用。 我已设法通过Job_ID升序和DATETIME下降到临时表( #JOB_HISTORY -note,使用:IDENTITY(int, 1,1)在临时表中生成pk_ID)按顺序放置作业历史记录,但是这里是我卡住的部分,我不知道如何对这张表中的记录进行排名。

SELECT 
  h1.pk_ID,
  h1.Job_ID,
  h1.Status,
  h1.DATETIME
FROM #JOB_HISTORY h1
ORDER BY h1.pk_ID ASC;

#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

期望的输出:

Job_ID    STATUS       DATETIME
1234      Succeded.    2015-03-30 12:10
5678      Failed.      2015-04-02 04:00

1 个答案:

答案 0 :(得分:0)

SQL Server可以自由地按照任何顺序插入记录,因此我不会信任IDENTITY(int, 1,1) 总是为您提供正确的序列。它可能在某些版本中有效。

您可以在内部加入子查询,在该查询中获取最大日期时间(或最小值pk_ID)以获取第一行/最后一行。这是获取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
;