基于现有表创建新表

时间:2014-12-02 15:31:28

标签: sql ms-access ms-access-2003

我正在尝试在Access 2003中编写一个基于现有表创建新表的查询。 我正在使用Make Table Query。

在:

NAME  A_1   A_2  B_1    B_2
X      1    2    3      4
Y      5    6    7      8

NAME    Section Value1  Value2  
X          A    1        2  
X          B    3        4  
Y          A    5        6  
Y          B    7        8  

1 个答案:

答案 0 :(得分:1)

创建SELECT查询,从现有表格的每一行检索 A_1 A_2 值:

SELECT e1.NAME, 'A' AS [Section], e1.A_1 AS Value1, e1.A_2 AS Value2
FROM tblExisting AS e1

然后创建一个类似的查询,检索 B_1 B_2 值,并UNION两个SELECT语句:

SELECT e1.NAME, 'A' AS [Section], e1.A_1 AS Value1, e1.A_2 AS Value2
FROM tblExisting AS e1
UNION ALL
SELECT e2.NAME, 'B' AS [Section], e2.B_1 AS Value1, e2.B_2 AS Value2
FROM tblExisting AS e2

从那里,您可以基于UNION查询构建一个make table查询:

SELECT sub.*
    INTO tblNew
FROM
    (
        SELECT e1.NAME, 'A' AS [Section], e1.A_1 AS Value1, e1.A_2 AS Value2
        FROM tblExisting AS e1
        UNION ALL
        SELECT e2.NAME, 'B' AS [Section], e2.B_1 AS Value1, e2.B_2 AS Value2
        FROM tblExisting AS e2
    ) AS sub;