I have a mysql table as shown below,
id reasonCode
------ ------------------
1 0, 1
2 0
3 1, 2, 3
4
...the num of reason codes are going to change. User can add/remove reason codes whenever he wants...
If what numbers would be there as part of reason codes is not known, then you better generate the query dynamic. You can do this by a stored procedure.
Steps to follow:
select
with found code and its count as 1.Union all
all such statements if generated some.Part of sample code snippet:
-- ...
set @sql_query := 'select reason_code, sum(rc_count) as rc_count from (' ;
set @sql_query :=
concat( @sql_query,
'\n ( select null as reason_code, 0 as rc_count )' );
-- ...
splitting_reason_codes: loop
set comma_position = locate( ',', reason_code_string );
if comma_position then
set rc := substring( reason_code_string, 1, comma_position-1 );
set reason_code_string :=
substring( reason_code_string, comma_position+1 );
else
set rc := reason_code_string;
end if;
if length( rc ) > 0 then
set @sql_query :=
concat( @sql_query,
'\n union all ( select ', rc, ', 1 )' );
end if;
if ! comma_position then
leave splitting_reason_codes;
end if;
end loop splitting_reason_codes;
-- ...
set @sql_query := concat( @sql_query, '\n) unique_reason_codes' );
set @sql_query := concat( @sql_query, '\nwhere reason_code is not null' );
set @sql_query := concat( @sql_query, '\ngroup by reason_code' );
set @sql_query := concat( @sql_query, '\norder by reason_code' );
prepare stmt from @sql_query;
execute stmt;
Demo @ SQL Fiddle