SQL Query,如何根据过滤器(日期)+条件(状态)

时间:2017-12-06 15:47:59

标签: sql sql-server tsql

我正在尝试从包含作业信息的表中查询失败的作业

让我们说它的备份作业表(backupInfoTable)(简化了问题)

jobName  | instanceName | status | date
________________________________________
one    |first instance| failed    | 12/16/2017
one    |first instance| success   | 1/1/2017
one    |secondInstance| failed    | 1/1/2017
one    |third instance| success   | 12/14/2017
two    |first instance| success   | 1/1/2017
two    |first instance| failed    | 1/1/2016
three  |first instance| failed    | 12/14/2017

我想只查询最近备份是失败备份的记录。 如果最近的备份成功,则它不相关,查询应该忽略它。

例如,查询结果应为:

one    |first instance| failed    | 12/16/2017
one    |secondInstance| failed    | 1/1/2017
three  |first instance| failed    | 12/14/2017

谢谢!

1 个答案:

答案 0 :(得分:12)

  

我想只查询最近备份是失败备份的记录。

类似的东西:

with q as
(
    select jobName, instanceName, jobStatus, date,
           row_number() over (partition by jobName, instanceName order by date desc) rn
    from backupInfotable
)
select jobName, instanceName, jobStatus, date
from q
where rn = 1 
  and jobStatus = 'failed'