如何利用Gaps and Islands模式获取最新状态孤岛数据
提取状态变更表的最新孤岛记录
我有一张记录状态变更的表,需要划分孤岛(Islands),最终获取基于状态变更时间的最新孤岛。目前已经编写了如下SQL查询,通过LAG和LEAD函数获取当前、前序及后续状态码,并标记孤岛起始标识:
select *, case when ping.GpsStatusTypeId <> ping.previousStatus then 1 else 0 end as islandStarted from (select Id, GpsStatusTypeId, CreatedAt, lag(GpsStatusTypeId, 1) over (order by CreatedAt) as previousStatus, lead(GpsStatusTypeId, 1) over (order by CreatedAt) as nextStatus from dbo.GpsPing p) ping
查询结果
| Id | GpsStatusTypeId | CreatedAt | previousStatus | nextStatus | islandStarted |
|---|---|---|---|---|---|
| 78E8C372-B7BE-4EED-8600-4925E7B66DBF | 6 | 2025-04-23 20:31:10.917 | 6 | 21 | 0 |
| 5CB42B3F-2542-4372-A169-5B664D971152 | 21 | 2025-04-23 17:46:40.217 | 6 | 21 | 1 |
| F57421EF-43AE-42C5-B766-C1CC07277B2E | 21 | 2025-04-24 15:50:38.000 | 21 | 21 | 0 |
| 3C07F71E-39EF-4728-B0EF-DF8E5B9AE529 | 21 | 2025-04-24 17:07:38.000 | 21 | 21 | 0 |
| 5CB42B3F-2542-4372-A169-5B664D971152 | 21 | 2025-04-24 17:08:38.000 | 21 | NULL | 0 |
现需从上述结果中提取最后一个孤岛(即GpsStatusTypeId=21的所有记录)。
内容的提问来源于stack exchange,提问作者GH DevOps
相关产品推荐
相关产品推荐

