这是我当前的表格
╔══════╦═══╦═══╦═══╦═════╦════╗
║ YEAR ║ A ║ B ║ C ║ ... ║ ZZ ║
╠══════╬═══╬═══╬═══╬═════╬════╣
║ 1995 ║ 1 ║ 0 ║ 1 ║ ... ║ 1 ║
║ 1996 ║ 1 ║ 1 ║ 0 ║ ... ║ 0 ║
╚══════╩═══╩═══╩═══╩═════╩════╝
该表包含大约1000列。现在我需要编写一个代码来将这个表旋转到一个更合理的表中,其中我表示的值表示为1.所以结果表应该像
╔══════╦════════╦═══════╗
║ YEAR ║ COLUMN ║ VALUE ║
╠══════╬════════╬═══════╣
║ 1995 ║ A ║ 1 ║
║ 1995 ║ C ║ 1 ║
║ 1995 ║ ZZ ║ 1 ║
║ 1996 ║ A ║ 1 ║
║ 1996 ║ B ║ 1 ║
╚══════╩════════╩═══════╝
所以通过谷歌搜索,我开始创建一个如下的SQL
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE v_du **???** DEFAULT "";
DEClARE du_cursor CURSOR FOR SELECT * FROM date_usage;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;
OPEN du_cursor;
get_du: LOOP
FETCH du_cursor INTO v_du;
IF v_finished = 1 THEN
LEAVE get_du;
END IF;
SHOW v_du; <<---
END LOOP get_du;
CLOSE du_cursor;
END
但问题是我不确定如何将v_du指定为列,我不确定我将如何读取列名。我们将不胜感激。
Thankx
答案 0 :(得分:3)
最简单的方法是使用一堆union all
语句:
select year, 'A' as column, A as value from table where A > 0 union all
select year, 'B' as column, B as value from table where B > 0 union all
. . .
select year, 'ZZ' as column, ZZ as value from table where ZZ > 0;
我会使用information_schema.columns
列出列,并使用Excel生成代码。
对大型表格使用效率更高的方法是cross join
:
select year, col,
(case when col = 'A' then A
when col = 'B' then B
. . .
when col = 'ZZ' then ZZ
end) as value
from table t cross join
(select 'A' as col union all select 'B' union all . . . select 'ZZ') cols
having value > 0;
答案 1 :(得分:1)
如果要将数据迁移到新表,请按以下方式执行:
INSERT INTO new_table(`year`, `column`, `value`) SELECT year, 'A', A FROM oldTable WHERE A > 0;
INSERT INTO new_table(`year`, `column`, `value`) SELECT year, 'B', B FROM oldTable WHERE B > 0;
INSERT INTO new_table(`year`, `column`, `value`) SELECT year, 'C', C FROM oldTable WHERE C > 0;
重复所有列名称。