2014-12-02 64 views
1

我想在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

創建SELECT查詢,從現有的表的每一行中檢索A_1A_2值:

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

然後創建以檢索B_1B_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查詢生成表查詢:

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;