7

如何选择 ID1 值按顺序(两个或多个)与 TOWN 匹配的记录

我的桌子

TOWN    ID1
town1   1
town1   2
town1   4 
town2   1
town2   5 
town2   8 
town3   1 
town3   2 
town3   3 

要求的结果

TOWN    ID1
town1   1
town1   2
town3   1 
town3   2 
town3   3 

sql小提琴

http://sqlfiddle.com/#!2/b409f/26

4

2 回答 2

7

您可以使用EXISTS子句检查序列中的下一个值。此代码将仅匹配长度 >= 2 的“序列”,这似乎是您从示例中想要的。

SELECT * 
  FROM Table1 a 
 WHERE EXISTS (SELECT * 
                 FROM Table1 b 
                WHERE b.TOWN=a.TOWN 
                  AND b.ID1 IN (a.ID1 - 1, a.ID1 + 1))
 ORDER BY TOWN, ID1
于 2013-09-18T14:15:18.317 回答
3

如果您的问题是“给我所有与城镇相邻id1的行”,那么只需:

select distinct t1.*
from Table1 t1
join Table1 t2 on t2.town = t1.town and ABS(t1.ID1 - t2.ID1) = 1
order by 1, 2

请参阅SQLFiddle


要在另一列上也匹配,请将条件添加到联接中,例如:

select distinct t1.*
from Table1 t1
join Table1 t2
  on t2.town = t1.town
  and t2.state = t1.state
  and ABS(t1.ID1 - t2.ID1) = 1
order by 1, 2
于 2013-09-18T14:37:38.367 回答