0

有选择地拆分数据

我有一个包含以下字段的表

表格1

Publication_ID, Student_ID, Q1,A1,Q2,A2,Q3,A3,Q4,A4......................Q249,A249,Q250,A250

样本数据

100, 123, 1, B, 2, A, 3, C,4, B, 5, D, 6, B,..........................120, C
100, 124, 1, C, 2, C, 3, D,4, C, 5, D, 6, B,.....................109, B
100, 125, 1, B, 2, C, 3, C,4, B, 5, D, 6, A,..........................120, C
100, 126, 1, C, 2, B, 3, A,4, B, 5, C, 6, D,..............................................250, D

现在我想以这种格式将表格上方的数据保存到另一个表格中

表 2

Publication_ID, Student_ID, Q,A
100, 123, 1,B
100, 123, 2,A
100, 123, 3,C
100, 123, 4,B
100, 123, 5,D
100, 123, 6,B
100, 124, 2,A
100, 124, 3,C
100, 124, 4,B
100, 124, 5,D
100, 124, 6,B
100, 125, 1,B
100, 125, 2,A
100, 125, 3,C
100, 125, 4,B
100, 125, 5,D
100, 125, 6,B


请注意,表 1 中填写的字段数对于所有数据行可能并不相同。所以它不应该将空字段从表 1 插入表 2

请在这方面帮助我

4

2 回答 2

1
INSERT INTO table-2(SELECT Publication_ID,Student_ID,Q1,Q2,....A1,A2... FROM table-1)

如果我理解正确

于 2013-07-29T17:20:57.797 回答
0

我假设您正在尝试规范化某种表格。因此,执行多个数据操作语句以达到预期结果应该不是问题。像这样的东西可能会奏效:

SET autocommit = 0

-- repeat for n for 1 to 249
INSERT INTO T2
  SELECT Publication_ID, Student_ID, Qn, An WHERE Qn IS NOT NULL

COMMIT

如果您确实需要在不使用宿主语言的情况下执行迁移,您可以使用以下过程:

CREATE PROCEDURE migrate()
BEGIN
  DELETE FROM T2;
  SET @n = 1;
  REPEAT
    SET @p = CONCAT('INSERT INTO T2 SELECT Publication_ID, Student_ID, Q', @n, ' as Q A', @n, ' WHERE Q IS NOT NULL');
    PREPARE stmt FROM @p;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    SET @n = @n+1;
  UNTIL @n > 249
  END REPEAT;
END //

CALL migrate()
于 2013-07-29T19:20:25.597 回答