mercredi 1 juillet 2020

MySQL Tagging Rows in Sequence based on a pattern

I have a column which I am trying to convert in MySQL into another column with a pattern where ever there are consecutive 1s in the data. Please see the example dataset below

Dataset Sample: https://1drv.ms/x/s!ApGNZAoiMmX3gi9OR7SUxt3ou84v?e=tuSV7f

example data with input and desired output

Following is the code I have written but not able to make it work and any suggestions would be helpful.

select rownum,result,movingsum,new_result
(select rownum,result,movingsum,
    if(result_norm_max=0,0,if(movingsum=1,1,0)) as new_result
from 
    (select rownum,result,
    sum(result) over (order by rownum rows between 2 preceding and current row) as movingsum
    from mytable) a;

The issue is, the above code doesn't return the output needed for all required logic of:

  • when result column is 0 new_result should be 0
  • when result is 1, new_result = 1 but only when previous 2 new_results are 0

Any suggestion on how I should approach this will be useful. Thanks!

Aucun commentaire:

Enregistrer un commentaire