sql - 如何获得每个岛屿的第一排和最后一排?
问题描述
所以我最近在一个问题上得到了很好的帮助。但是,我需要更精确一些,希望这在 SQL 中是可行的。
这是我的最后一个问题:
澄清:
我在那个问题上得到的帮助是让我开始每个岛屿。但是,我想要每个岛的起点和终点。
我的细微差别是这样的:
personID | status | unixtime | column d | column e | column f
1 2 213214 x y z
1 2 213325 x y z
1 2 213326 x y z
1 2 213327 x y z
1 2 213328 x y z <-- I want this
1 3 214330 x y z <-- Any of this is OK
1 3 214331 x y z
1 3 214332 x y z <-- I want this or
1 2 324543 x y z <-- I want this
所以我想要的是岛的尽头,而不是岛屿的起点。如果我在两者之间得到一些东西,那完全没问题,最好是结束。但是我真的想要状态变化的“之前”和“之后”是什么,如果这有任何意义的话。这可能是一个特定的状态。
解决方案
select t.*
from (select t.*,
case when status <> lag(status,1,NULL) over(partition by personID order by unixtime)
then 1
when lag(status,1,NULL) over(partition by personID order by unixtime) is null
then 1
else 0 end as start_status,
case when status <> lead(status,1,NULL) over(partition by personID order by unixtime)
then 1
when lead(status,1,NULL) over(partition by personID order by unixtime) is null
then 1
else 0 end as end_status
from mytable t
) t
where end_status = 1
--or start_status = 1 -- uncomment this line if you want start statuses as well
推荐阅读
- excel - 如何解决错误代码:“404”,消息:“使用 Azure 逻辑应用向 Excel 文件添加行时请求的资源不存在?
- javascript - 使用 vanilla javascript 更改购物车中的购物车项目数量
- r - R中的data.table问题(列指定不存在的列)
- java - 10.5f 和 (float)10.5 的区别
- database - 尝试在 Flutter 中打开数据库时对“this”表达式的引用无效
- r - 试图遍历一个列表来做重复的突变
- postgresql - 将 postgresql 连接到其他硬盘上的数据库
- arrays - 试图让我的对象中的对象将它们的 id 用于我的 useState
- java - 在 Thymeleaf 表中显示多行
- linux - 为什么在 Debian 中有不同的方法来重启 apache2 和网络?