how to find repeated value and count in mysql -
i have table 3 columns, how find value if appears next 3 times i.e 1st trnas_value appears in next 3 consecutive times (repeaded 4 times) , 2nd , 6th rows repeated same.date column sorted a_z
date tran_val name 23mar 22 mark 24mar 22 mark 25mar 22 mark 26mar 22 mark 27mar 22 mark 28jan 99 john 29jan 99 john 30jan 99 john 31jan 99 john
output
name trans_value consecutive_count mark 22 2 john 99 1
we have code not giving above output..
select name, tran_val, max(cnt - 3) consecutive_count ( select date, tran_val, name, @cnt:=if(@tran_val=tran_val , @name=name, @cnt + 1, 1) cnt, @tran_val:=tran_val, @name:=name some_table cross join (select @cnt:=0, @tran_val:=0, @name:='') sub0 order `date` ) sub1 group name, tran_val
any modification in above code desired output.thanks
try this:
select `tran_val`, `name`, count(*) - 3 ( select `date`, `tran_val`, `name`, rn - seq grp ( select `date`, `tran_val`, `name`, @rn := @rn + 1 rn, @seq := if(@name = `name` , @val = `tran_val`, @seq+1, 1) seq, @name := name, @val := tran_val mytable cross join (select @rn := 0, @seq := 0, @name = '', @val = 0) vars order `date`) t ) s group `tran_val`, `name`, grp having count(*) > 3
you need two separate variable enumerate sequences:
@rn
enumerates consecutive table rows@seq
enumerates consecutive table rows having samename
,tran_val
values.
the difference between these 2 variables, i.e. @rn
- @seq
, identifies islands of consecutive table rows having same name
, tran_val
values.
edit: added having
clause query filter out islands having population of 3 or less consecutive rows.
Comments
Post a Comment