Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query for grouping the data

I have a data set some thing like below.

Code          Values
521            1
522            1
523            1
524            0
525            0
526            1
527            1

I am expecting a output something like below:

Group     CD        Values
G1      521-523       1
G2      524-525       0
G3      526-527       1
like image 947
RAJ Avatar asked Feb 13 '26 13:02

RAJ


1 Answers

I would be inclined to use the difference of row numbers approach:

select concat('G', row_number() over (order by min(value)) as grp,
       concat(min(code), '-', max(code)) as codes,
       value
from (select t.*,
             row_number() over (order by code) as seqnum_c,
             row_number() over (partition by value order by code) as seqnum_vc
      from t
     ) t
group by value, (seqnum_c - seqnum_vc);
like image 121
Gordon Linoff Avatar answered Feb 16 '26 06:02

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!