Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 选择具有最新日志的记录_Sql_Sql Server 2008 - Fatal编程技术网

Sql 选择具有最新日志的记录

Sql 选择具有最新日志的记录,sql,sql-server-2008,Sql,Sql Server 2008,我试图在不运行内部查询的情况下完成此查询,但似乎无法正确获取记录 我有两个表(为了可读性更改了命名约定) 一个报告可以有多个状态日志。我正在尝试获取最新报告状态日志等于某个代码的所有报告 这行不通 select report.id inner join report_status_log on report.report_id = report_status_log.report_id where report_status_log.code = 'finished' 。。。因

我试图在不运行内部查询的情况下完成此查询,但似乎无法正确获取记录

我有两个表(为了可读性更改了命名约定)

一个报告可以有多个状态日志。我正在尝试获取最新报告状态日志等于某个代码的所有报告

这行不通

select report.id
       inner join report_status_log on report.report_id = report_status_log.report_id
where  report_status_log.code = 'finished'
。。。因为尽管“完成”可能在状态日志中,但它不一定总是最新的日志记录


有办法做到这一点吗?或者我应该从report\u status\u log table而不是report table中进行选择吗?

您不能使用时间戳上的max函数来获取最近的日志吗

with cte as (
  select *, 
    row_number() over (partition by report_id order by timestamp desc) as RowNum
  from report_status_log
)

select * 
from report r
inner join cte c
on r.report_id = c.report_id
where c.code = 'finished' and RowNum = 1
select report_id
from report
inner join report_status_log on report.report_id = report_status_log.report_id
where timestamp = (SELECT MAX(timestamp) FROM report_status_log)
and report_status_log.code = 'finished'

您不能只使用时间戳上的max函数来获取最近的日志吗

select report_id
from report
inner join report_status_log on report.report_id = report_status_log.report_id
where timestamp = (SELECT MAX(timestamp) FROM report_status_log)
and report_status_log.code = 'finished'

是的,这个问题在StackOverflow上非常常见。这是今天的第二次。当然,这是最合乎逻辑和最直接的方法。这很有效,但只能得到一条记录,不能100%确定为什么,这个问题在StackOverflow上异常常见。这是今天的第二次。当然,这是最符合逻辑和最直接的方法。这种方法有效,但只能得到一条记录,无法100%确定原因