Reputation: 12307
I have a zillion of colums that I need to convert into rows.
I have 3 main categories (CAT, ODB & GPA) Each category has a month (From Jan, to Dec) and each category has a year) Here is a sample of the structure:
CATJAN2002 | CATFEB2002...| CATDEC2002...| ODBJAN2003...| GPAMAR2013
In vba I can create a simple loop, to export this data into another table:
New_Table
fields:
ID, TYPE, YEAR, MONTH, VALUE
. Can YOU PLEASE help me find a way to automatically go thought the table's columns and start inputing the data into the new table? Can this be done in MySQL alone?
I forgot to menton that the combination of the first columns (STORE, ITEM & CUSTOMER ) is the ID (Or primary key) [SELECT CONCAT(STORE, ITEM, CUSTOMER) AS ID
Upvotes: 0
Views: 3499
Reputation: 49089
The idea is to use a query like this:
SELECT CONCAT(STORE, ITEM, CUSTOMER) ID,
'CAT' TYPE, 2002 YEAR, 'JAN' MONTH, CATJAN2002 VALUE
FROM yourtable
UNION ALL
SELECT CONCAT(STORE, ITEM, CUSTOMER) ID,
'CAT' TYPE, 2002 YEAR, 'FEB' MONTH, CATFEB2002 VALUE
FROM yourtable
UNION ALL
...
And you can make it using a dynamic query, like this:
SELECT
GROUP_CONCAT(
CONCAT(
'SELECT CONCAT(STORE, ITEM, CUSTOMER) ID,',
'\'',
LEFT(column_name, 3),
'\' TYPE,',
RIGHT(column_name, 4),
' YEAR, \'',
SUBSTR(column_name, 4, 3),
'\' MONTH,',
column_name,
' VALUE FROM yourtable')
SEPARATOR ' UNION ALL ')
FROM information_schema.COLUMNS
where
table_name = 'yourtable'
AND (column_name LIKE 'CAT%' OR column_name LIKE 'ODB%' OR column_name LIKE 'GPA%')
INTO @sql;
prepare stm from @sql;
execute stm;
Please see fiddle here.
Upvotes: 2