您寻求的解决方案的一般形式是使用 UNION 查询,如下所示:
SELECT [country], [product], [id],
[1qtr 2010 flash] AS [Value],
2010 AS [Year],
1 AS [Qtr],
"flash" AS [Type]
FROM ImportedTable
UNION ALL
SELECT [country], [product], [id],
[2qtr 2010 flash] AS [Value],
2010 AS [Year],
2 AS [Qtr],
"flash" AS [Type]
FROM ImportedTable
UNION ALL
SELECT [country], [product], [id],
[3qtr 2010 flash] AS [Value],
2010 AS [Year],
3 AS [Qtr],
"flash" AS [Type]
FROM ImportedTable
...
您可以使用 [ReformatDataFromExcel] 之类的名称保存此类查询,然后当您导入具有新列的更新 Excel 提要时,您可以根据需要通过复制和粘贴新的 UNION ALL 子句来更新查询。
- 编辑 -
或者,如果您想通过代码构建 SQL 查询字符串,那么像这样的一些 VBA...
Sub BuildQueries()
Dim cdb As DAO.Database, fld As DAO.Field, sSQL As String
Dim sYear As String, sQtr As String, sType As String, a() As String
Set cdb = CurrentDb
For Each fld In cdb.TableDefs("ImportedTable").Fields
Select Case fld.Name
Case "country", "product", "id"
' do nothing
Case Else
a = Split(fld.Name, " ", -1, vbBinaryCompare)
sQtr = Left(a(0), 1)
sYear = a(1)
sType = a(2)
sSQL = _
"SELECT [country], [product], [id], " & _
"[" & fld.Name & "] AS [Value], " & _
sYear & " AS [Year], " & _
sQtr & " AS [Qtr], " & _
"""" & sType & """ AS [Type] " & _
"FROM ImportedTable"
Debug.Print sSQL ' or whatever you want to do with the query
End Select
Next
Set fld = Nothing
Set cdb = Nothing
End Sub
...可以像这样构建 SQL 字符串:
SELECT [country], [product], [id], [1qtr 2010 flash] AS [Value], 2010 AS [Year], 1 AS [Qtr], "flash" AS [Type] FROM ImportedTable
SELECT [country], [product], [id], [2qtr 2010 flash] AS [Value], 2010 AS [Year], 2 AS [Qtr], "flash" AS [Type] FROM ImportedTable
SELECT [country], [product], [id], [3qtr 2010 flash] AS [Value], 2010 AS [Year], 3 AS [Qtr], "flash" AS [Type] FROM ImportedTable
SELECT [country], [product], [id], [4qtr 2010 flash] AS [Value], 2010 AS [Year], 4 AS [Qtr], "flash" AS [Type] FROM ImportedTable
SELECT [country], [product], [id], [1qtr 2011 budget] AS [Value], 2011 AS [Year], 1 AS [Qtr], "budget" AS [Type] FROM ImportedTable
SELECT [country], [product], [id], [2qtr 2011 budget] AS [Value], 2011 AS [Year], 2 AS [Qtr], "budget" AS [Type] FROM ImportedTable
SELECT [country], [product], [id], [3qtr 2011 budget] AS [Value], 2011 AS [Year], 3 AS [Qtr], "budget" AS [Type] FROM ImportedTable
SELECT [country], [product], [id], [4qtr 2011 budget] AS [Value], 2011 AS [Year], 4 AS [Qtr], "budget" AS [Type] FROM ImportedTable