Python 在给定唯一ID的情况下,仅选择列已从其前面的行更改的行

Python 在给定唯一ID的情况下,仅选择列已从其前面的行更改的行,python,sql,postgresql,window-functions,gaps-and-islands,Python,Sql,Postgresql,Window Functions,Gaps And Islands,我有一个postgreSQL数据库,我想在其中记录每个id的特定列随时间的变化。表1: personID | status | unixtime | column d | column e | column f 1 2 213214 x y z 1 2 213325 x y z 1 2 213326

我有一个postgreSQL数据库,我想在其中记录每个id的特定列随时间的变化。表1:

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
    1        3       214330      x            y        z
    1        3       214331      x            y        z
    1        3       214332      x            y        z
    1        2       324543      x            y        z
我希望跟踪随时间变化的所有状态。基于此,我想要一个新的表,表2包含以下数据:

personID | status | unixtime | column d | column e | column f
    1        2       213214      x            y        z
    1        3       214323      x            y        z
    1        2       324543      x            y        z
x、 y、z是可以并且将在每行之间变化的变量。这些表中还有数千个其他人,他们的ID不断变化,我也想捕捉到。在我看来,按状态分组personid是不够的,因为我可以存储多行相同的状态和personid,就像状态发生了变化一样

我是用Python实现的,但是速度非常慢,而且我想它需要很多IO:

for person in personid:
    status = -1
    records = getPersonRecords(person) #sorted by unixtime in query
    newrecords = []
    for record in records:
        if record.status != status:
                 status = record.status
                 newrecords.append(record)
    appendtoDB(newrecords)

这是一个缺口和孤岛问题。您需要每个孤岛的开始,您可以通过比较当前行上的状态和上一条记录上的状态来识别该孤岛

窗口功能在这方面很方便:

select t.*
from (
    select t.*, lag(status) over(partition by personID order by unixtime) lag_status
    from mytable t
) t
where lag_status is null or status <> lag_status

非常感谢。一个简单的问题-有可能有每个岛屿的尽头吗?我知道我的问题中没有具体说明,但现在我想到了。可能只按unixtime desc排序?