选择上一行发生更改的记录

the*_*ide 0 sql postgresql

我有一个psql表调用test三个属性列.第一种类型是整数,第二种是字符,第三种是整数

我的目标是只选择其中的状态已经从记录ABC-换句话说,在当前状态C与以前的状态要么A或者B,通过有序id和记录编号.

如何在psql中编写这样的查询?

 id state record
  1     C      1
  1     A      2
  1     C      3
  1     A      4
  1     C      5
  1     A      6
  1     B      7
  2     C      8
  2     C      9
  2     C     10
  2     B     11
  2     C     12
  2     C     13
  2     C     14
  3     A     15
  3     C     16
  3     B     17
  3     A     18
  3     A     19
  3     A     20
  3     A     21
  3     C     22
  3     A     23
  3     B     24
  3     B     25
Run Code Online (Sandbox Code Playgroud)

上面的SELECTING将返回如下内容:

id state record
  1     C      3
  1     C      5
  2     C     12
  3     C     16
  3     C     22
Run Code Online (Sandbox Code Playgroud)

Gor*_*off 6

一种方法使用lag():

select t.*
from (select t.*, lag(t.state) over (partition by t.id order by t.record) as prev_state
      from t
     ) t
where t.state = 'C' and prev_state in ('A', 'B');
Run Code Online (Sandbox Code Playgroud)

另一个使用自联接:

select t.*
from t join
     t tprev
     on t.id = tprev.id and t.record = t.record + 1
where t.state = 'C' and tprev.state in ('A', 'B')
Run Code Online (Sandbox Code Playgroud)