SQL to club records in sequence

Viewed 44

I have data in MySQL table, my data looks like

Key, value
  A   1
  A   2
  A   3
  A   6
  A   7
  A   8
  A   9
  B   1
  B   2

and I want to group it based on the continuous sequence. Data is sorted in the table.

Key, min, max
  A   1    3
  A   6    9
  B   1    2

I tried googling it but could find any solution to it. Can someone please help me with this.

1 Answers

This is way easier with a modern DBMS that support window functions, but you can find the upper bounds by checking that there is no successor. In the same way you can find the lower bounds via absence of a predecessor. By combining the lowest upper bound for each lower bound we get the intervals.

select low.keyx, low.valx, min(high.valx) 
from (  
  select t1.keyx, t1.valx from t t1
  where not exists (
    select 1 from t t2
    where t1.keyx = t2.keyx
      and t1.valx = t2.valx + 1
  )
) as low
join (  
  select t3.keyx, t3.valx from t t3
  where not exists (
    select 1 from t t4
    where t3.keyx = t4.keyx
      and t3.valx = t4.valx - 1
  )
) as high
  on low.keyx = high.keyx
  and low.valx <= high.valx
group by low.keyx, low.valx;

I changed your identifiers since value is a reserved world.

Using a window function is way more compact and efficient. If at all possible, consider upgrading to MySQL 8+, it is superior to 5.7 in so many aspects.

We can create a group by looking at the difference between valx and an enumeration of the vals, if there is a gap the difference increases. Then, we simply pick min and max for each group:

select keyx, min(valx), max(valx)
from (  
  select keyx, valx
     , valx - row_number() over (partition by keyx order by valx) as grp
  from t
) as tt
group by keyx, grp;   

Fiddle

Related