How to create select dynamic fields from a table in mysql?

后端 未结 2 857
忘掉有多难
忘掉有多难 2020-12-12 04:26

I have query join in select statement like this :

select a.item_number, total_quantity, store, factory
from (
    select item_number, sum(quantity) as \"tot         


        
2条回答
  •  猫巷女王i
    2020-12-12 05:11

    This is not tested ,create a fiddle if you find errors.

    SELECT
      GROUP_CONCAT(DISTINCT
        CONCAT(
          'ifnull(SUM(case when location_code = ''',
          location_code ,
          ''' then quantity end),0) AS `',
          location_code , '`'
        )
      ) INTO @sql
    FROM
      item_details;
    SET @sql = CONCAT('SELECT item_number,SUM(quantity) as "total_quantity", ', @sql, ' 
                      FROM item_details
                       GROUP BY item_number');
    
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    
    DEALLOCATE PREPARE stmt;
    

提交回复
热议问题