我只想选择name1列中更改为name1列的任何值的ID,具体取决于最后2个ID。因此,请参见以下逻辑:
示例1:
ID NAME1 NAME2
102 A AA
101 A AA
100 A AA
102 B BB
101 B AA
100 B CC
结果应为:100, 101 (after comparison of 100 and 101), 102 (after comparison of 101 and 102)
示例2:
ID NAME1 NAME2
102 A AA
101 A AA
100 A AA
102 B AA
101 B AA
100 B CC
结果应为:100, 101 (after comparison of 100 and 101) , 102 is not shown because it hasn't changed when we compare 101 and 102.
仍然应该选择最小的ID。
请参阅下面的SQL Fiddle:
http://sqlfiddle.com/#!4/1735c/1
谢谢!
我不确定逻辑,但据我所知,您可以按以下方式使用lag
和lead
:
Select * from
(Select t.*,
Lag(name2) over (partition by name1 order by id desc) as lg,
Lead(name2) over (partition by name1 order by id desc) as ld
From your_table t)
Where lg is not null
and (lg <> name2
Or (ld is not null
and ld <> name2));
干杯!