mysql Count multiple occurrences of multiplexed entries

前端 未结 3 1131
甜味超标
甜味超标 2021-01-28 23:54

I have a mysql table as shown below,

  id          reasonCode
------      ------------------
  1           0, 1
  2           0
  3           1, 2, 3
  4                 


        
3条回答
  •  执笔经年
    2021-01-29 00:48

    ...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:

    1. Fetch each reason code string in to a variable.
    2. Split it to find each of the reason codes.
    3. Generate a select with found code and its count as 1.
    4. Union all all such statements if generated some.
    5. Loop until no more codes are present in each string.
    6. Repeat until all rows are processed
    7. Now, run an aggregate function on the generated result sets group by reason code.
    8. You have the results in hand.

    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

提交回复
热议问题