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
If you are using stored procedure then your query will become easy to use dynamically.
Dynamic column name you can manage by integer number or name of columns.
store your existing query in the variable and use If condition to concat your dynamic query
in variable. at last execute the statement by defined variable.
you can take reference from below link for execute the dynamic code. mysql dynamic query in stored procedure
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;