MySQL 根据模式标记序列中的行
MySQL Tagging Rows in Sequence based on a pattern
我有一个列,我试图将其在 MySQL 中转换为另一列,其模式在数据中有连续的 1。请参阅下面的示例数据集
数据集示例:https://1drv.ms/x/s!ApGNZAoiMmX3gi9OR7SUxt3ou84v?e=tuSV7f
以下是我编写的代码,但无法使其正常工作,任何建议都会有所帮助。
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;
问题是,上面的代码没有return所有必需逻辑所需的输出:
- 当结果列为 0 时 new_result 应为 0
- 当结果为 1 时,new_result = 1 但仅当前 2 个 new_result 为 0
任何关于我应该如何处理这个问题的建议都会很有用。
谢谢!
经过一些尝试,我找到了接近我需要的解决方案,如下所述。我使用了 2 个变量来实现这个技巧,
select rownum,result,
if (result= 0, 0, if(@n = 1, if(@m >= 7, 1 , 0), 1)) as new_max,
if (result= 0, 0, if(@n = 1,
case when @m >= 7 then @m:=0 else 0 end
, 1)) as new_max1,
if (result= 0, if(@m>0,@m:=@m-1,@m:=0), if(@n = 1, @m:=@m+1,@m:=@m-1)) as new_m,
@n := result
from mytable a, (select @n:= 0, @m:= 0) b
我有一个列,我试图将其在 MySQL 中转换为另一列,其模式在数据中有连续的 1。请参阅下面的示例数据集
数据集示例:https://1drv.ms/x/s!ApGNZAoiMmX3gi9OR7SUxt3ou84v?e=tuSV7f
以下是我编写的代码,但无法使其正常工作,任何建议都会有所帮助。
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;
问题是,上面的代码没有return所有必需逻辑所需的输出:
- 当结果列为 0 时 new_result 应为 0
- 当结果为 1 时,new_result = 1 但仅当前 2 个 new_result 为 0
任何关于我应该如何处理这个问题的建议都会很有用。 谢谢!
经过一些尝试,我找到了接近我需要的解决方案,如下所述。我使用了 2 个变量来实现这个技巧,
select rownum,result,
if (result= 0, 0, if(@n = 1, if(@m >= 7, 1 , 0), 1)) as new_max,
if (result= 0, 0, if(@n = 1,
case when @m >= 7 then @m:=0 else 0 end
, 1)) as new_max1,
if (result= 0, if(@m>0,@m:=@m-1,@m:=0), if(@n = 1, @m:=@m+1,@m:=@m-1)) as new_m,
@n := result
from mytable a, (select @n:= 0, @m:= 0) b