首页 > 解决方案 > 如何获得每个岛屿的第一排和最后一排?

问题描述

所以我最近在一个问题上得到了很好的帮助。但是,我需要更精确一些,希望这在 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

所以我想要的是岛的尽头,而不是岛屿的起点。如果我在两者之间得到一些东西,那完全没问题,最好是结束。但是我真的想要状态变化的“之前”和“之后”是什么,如果这有任何意义的话。这可能是一个特定的状态。

标签: sqlpostgresqlgaps-and-islands

解决方案


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

推荐阅读