简体   繁体   English

MySQL:将列转换为行

[英]MySQL: Convert column into rows

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: 我有3个主要类别(CAT,ODB和GPA)每个类别有一个月(从1月到12月),每个类别有一年)以下是结构示例:

CATJAN2002 | CATJAN2002 | CATFEB2002...| CATFEB2002 ... | CATDEC2002...| CATDEC2002 ... | ODBJAN2003...| ODBJAN2003 ... | GPAMAR2013 GPAMAR2013

In vba I can create a simple loop, to export this data into another table: 在vba中我可以创建一个简单的循环,将这些数据导出到另一个表中:

New_Table fields: ID, TYPE, YEAR, MONTH, VALUE . New_Table字段: 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? 这可以单独在MySQL中完成吗?

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 我忘记了第一列(STORE,ITEM和CUSTOMER)的组合是ID(或主键)[ SELECT CONCAT(STORE, ITEM, CUSTOMER) AS ID

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 . 请看这里的小提琴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM