oba*_*sta 2 sql-server sql-server-2014
如何比较以前记录的值?
桌子:
ID SAMPLEDATE LEVEL PASSED
1 1/1/2016 0 1
2 1/2/2016 1 1
3 1/3/2016 2 0
4 1/4/2016 1 1
5 1/5/2016 2 0
Run Code Online (Sandbox Code Playgroud)
最后一条记录(由 排序SAMPLEDATE
)是否与最后LEVEL
一条失败的记录相同?如果是,则返回 TRUE,否则返回 FALSE。
因此,在我的示例数据中,最后一条记录失败并显示为LEVEL
2。然后在 2016 年 1 月 3 日失败的最后一条记录(在 2016 年 1 月 5 日之前)是相同的 LEVEL,因此将返回 TRUE。如果是不同的 LEVEL FALSE 将被返回。
我认为“失败”意味着passed = 0
.
问题中缺少一些细节,即我们是否需要将最后一行(按 排序sampledate
)与之前最后一个“失败”行进行比较?如果是,则以下查询将执行:
with last_row as
( select top (1) sampledate, level
from dbo.tablex
-- where failed = 0
order by sampledate desc
)
select top (1) result =
case when t.level = r.level
then 1 else 0
end
from dbo.tablex as t
join last_row as r
on t.sampledate < r.sampledate
where t.passed = 0
order by t.sampledate desc ;
Run Code Online (Sandbox Code Playgroud)
另一方面,如果我们想将最后一个“失败”行与前一个“失败”行进行比较,那么我们可以取消注释where failed = 0
上面的行或使用不太复杂的行,只需找到最后 2 个失败的行并将它们的级别与一个简单的group by
:
with last_2_failed_rows as
( select top (2) sampledate, level
from dbo.tablex
where failed = 0
order by sampledate desc
)
select result =
case when min(level) = max(level)
then 1 else 0
end
from last_2_failed_rows ;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1757 次 |
最近记录: |