仅选择已更改的行

Kar*_*dén 3 sql sql-server postgresql

我的行看起来像这样:

1
0 ----> Change! This row is of interest
1 ----> Change again.
1
1
1
1
1
0 ----> Change.
1 ----> Change.
Run Code Online (Sandbox Code Playgroud)

新的 1 之前可能有一百万个零,我只想要更改(标有更改的行)。这会给我带来大约少 1000 万行的结果。我们支持 SQLServer 和 PostGresSQL。它按时间戳列排序。0 为系统离线标志,1 为系统在线。服务会定期报告此信息并为其添加时间戳。

有任何想法吗?编辑:还有很多其他列,其中之一是确定顺序的时间戳列。0 为系统离线标志,1 为系统在线。服务会定期报告此信息并为其添加时间戳。

干杯

小智 6

好的。因此,根据评论我们知道有时间戳列。我们假设它被命名为“event_when”,并且 0/1 列被命名为“status”。

所以我们可以:

with x as (
    select
        *,
        lag(status) over (order by event_when) is distinct from status as interesting
    from table
)
select * from x where interesting;
Run Code Online (Sandbox Code Playgroud)

  • SQL Server 引入了 LEAD 和 LAG:http://blog.sqlauthority.com/2011/11/15/sql-server-introduction-to-lead-and-lag-analytic-functions-introduced-in-sql-server-2012 / (2认同)