如何从大表中选择行对?

时间:2012-11-27 03:28:48

标签: sql sqlite select

表格.....(ID,NAME,EVENT)

数据:

(1,BOB,E)    
(2,JANE,B)    
(3,JOE,C)    
(4,TOM,A)   
(5,JANE,B)    
(6,JOE,C)    
(7,BEN,D)    
(8,TOM,B)    
(9,JANE,D)    
(10,JOE,A)    
(11,JANE,B)    
(12,BOB,C)    
(13,JOE,C)    
.    
.    
.

期望的输出:

(2,JANE,B)    
(3,JOE,C)    
(5,JANE,B)    
(6,JOE,C)

我正在尝试列出Jane,B和Joe,C连续出现在表格中的每个实例。使用sqlite。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用标准SQL执行此操作,该SQL也适用于SQLite。我们的想法是将给定行连接到下一行和上一行,然后检查条件:

select t.*
from t join
     t tnext
     on tnext.id = t.id + 1 join
     t tprev
     on tprev.id = t.id - 1
where (t.name = 'Jane' and t.event = 'B' and tnext.name = 'Joe' and tnext.event = 'C') or
      (tnext.name = 'Jane' and tnext.event = 'B' and t.name = 'Joe' and t.event = 'C') or
      (t.name = 'Jane' and t.event = 'B' and tprev.name = 'Joe' and tprev.event = 'C') or
      (tprev.name = 'Jane' and tprev.event = 'B' and t.name = 'Joe' and t.event = 'C')