sql >> Base de Datos >  >> RDS >> Mysql

Derivar nuevos campos que lleven conteos para cada registro

select
P1_id,
P2_id,
Outcome_for_P1,
P1_W,
P1_L,
P1_D,
Day
from (
 select c.*,
 @w:= if(@prev_p1 = P1_id, if(Outcome_for_P1 = 'W',@w+1,@w),if(Outcome_for_P1 = 'W',1,0)) as P1_W,
 @l:= if(@prev_p1 = P1_id, if(Outcome_for_P1 = 'L',@l+1,@l),if(Outcome_for_P1 = 'L',1,0)) as P1_L,
 @d:= if(@prev_p1 = P1_id, if(Outcome_for_P1 = 'D',@d+1,@d),if(Outcome_for_P1 = 'D',1,0)) as P1_D, 
 @prev_p1:= P1_id
 from chess c,(select @w:=0,@l:=0,@d:=0,@prev_p1:=0)x
 order by P1_id asc, Day asc
)x
order by P1_id asc, Day asc;