SQL选择值更改的行

时间:2018-10-11 22:03:52

标签: sql sql-server sql-server-2008

我有一张这样的桌子:

id     |   diameter
___________________
100    |     5.0             
101    |     5.0                      
102    |     3.0             
103    |     3.0         
104    |     3.0         
105    |     6.0       
106    |     6.0

SELECT a.* FROM tableX AS a WHERE a.diameter <> ( SELECT TOP 1 b.diameter FROM tableX AS b WHERE a.id > b.id ORDER BY b.id )             

我需要查询以显示直径变化的地方的ID。在此示例中,我将需要它显示id 102和id 105

2 个答案:

答案 0 :(得分:3)

您要在SQL Server 2012+中使用lag()

select t.*
from (select t.*, lag(t.diameter) over (order by t.id) as prev_diameter
      from t
     ) t
where prev_diameter <> diameter;

在SQL Server 2008中,可以使用相关子查询或apply

select t.*
from t cross apply
     (select top (1) t2.*
      from t t2
      where t2.id < t.id
      order by t2.id desc
     ) tprev
where tprev.diameter <> t.diameter

答案 1 :(得分:-1)

您需要遍历所有记录,并比较prev_Record = curr_Record。如果条件为假,则将其保存到@temp变量中,然后在最后将其返回