Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

sql - How can I find duplicate consecutive values in this table?

Say I have a table which I query like so:

select date, value from mytable order by date

and this gives me results:

date                  value
02/26/2009 14:03:39   1                
02/26/2009 14:10:52   2          (a)
02/26/2009 14:27:49   2          (b)
02/26/2009 14:34:33   3
02/26/2009 14:48:29   2          (c)
02/26/2009 14:55:17   3
02/26/2009 14:59:28   4

I'm interested in the rows of this result set where the value is the same as the one in the previous or next row, like row b which has value=2 the same as row a. I don't care about rows like row c which has value=2 but does not come directly after a row with value=2. How can I query the table to give me all rows like a and b only? This is on Oracle, if it matters.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the lead and lag analytic functions.

create table t3 (d number, v number);
insert into t3(d, v) values(1, 1);
insert into t3(d, v) values(2, 2);
insert into t3(d, v) values(3, 2);
insert into t3(d, v) values(4, 3);
insert into t3(d, v) values(5, 2);
insert into t3(d, v) values(6, 3);
insert into t3(d, v) values(7, 4);

select d, v, case when v in (prev, next) then '*' end match, prev, next from (
  select
    d,
    v,
    lag(v, 1) over (order by d) prev,
    lead(v, 1) over (order by d) next
  from
    t3
)
order by
  d
;

Matching neighbours are marked with * in the match column,

alt text


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...