2015-08-13 104 views
0

我有.db文件包含線程表看起來像這樣一個SQLite:SQLite的查詢GROUP BY附近排

ThreadID ClusterID 
1   0 
2   0 
3   0 
4   1 
5   1 
6   0 
7   1 
8   1 
9   0 
10  1 

而且我想GROUP BY的羣ID只與附近行。輸出將是:

ThreadID ClusterID 
1   0  
4   1 
6   0 
7   1 
9   0 
10  1 

或理想:

ThreadID ClusterID ClusterSwitch 
1   0   NO 
2   0   NO 
3   0   NO 
4   1   YES 
5   1   NO 
6   0   YES 
7   1   YES 
8   1   NO 
9   0   YES 
10  1   YES 

整個設計其檢測當羣集從0切換到1和1比0

感謝您的幫助是真的很感激:) -Steve

回答

1

假設你的線程ID確實沒有間隙,你可以使用自加入:

select t.*, 
     (case when tprev.clusterid <> t.clusterid then 1 else 0 end) as ClusterSwitch 
from threads t left join 
    threads tprev 
    on t.threadid = tprev.threadid + 1; 

如果你不能確保沒有縫隙,可以用相關子查詢做到這一點:

select t.*, 
     (case when t.clusterid <> 
        (select t2.clusterid 
        from threads t2 
        where t2.id < t.id 
        order by t2.id desc 
        limit 1 
       ) 
      then 1 else 0 end) as ClusterSwitch 
from threads t; 

然而,這個查詢將不能很好地擴展,因此性能可能是一個問題。

+0

非常感謝你..它的竅門! –