0

I want to query only numbers which are repeated 3 times consecutively like 1 here. But not 2 as it is not consecutive.

How can i achieve same in sql?

Kshitish Das
  • 67
  • 1
  • 7

2 Answers2

2

SQL table represent unordered sets (well, technically multisets). Assuming that your "list" is stored as rows in a table and there is an ordering column, then you can use lead():

select distinct number
from (select t.*,
             lead(number) over (order by <ordering col>) as next_number,
             lead(number, 2) over (order by <ordering col>) as next_number_2
      from t
     ) t
where number = next_number and number = next_number_2;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

If the data is stored as rows in a table Gordon's logic can be simplified and modified for any number of repetitions:

select distinct number
from t
qualify
   -- same value in the last n rows, n=3
   min(number) over (order by <ordering col> rows 2 preceding) =
   max(number) over (order by <ordering col> rows 2 preceding)
   -- to avoid false positives for the first n-1 rows
and count(number) over (order by <ordering col> rows 2 preceding) = 3
dnoeth
  • 59,503
  • 4
  • 39
  • 56