我们需要做的第一件事是通过 UNION 查询将数据从“少行多列”转换为“少列多行”。(我将您的测试数据保存在一个名为 [N_column_table] 的表中。)
SELECT [year], "President" AS office, [President] AS person
FROM [N_column_table]
UNION ALL
SELECT [year], "Vice" AS office, [Vice] AS person
FROM [N_column_table]
如果将该查询保存为“3_column_data”,那么您可以像在其他查询、报告等中使用表一样使用它。(UNION ALL
当您为真实数据构建查询时,您将不得不添加大约 8 个构造。)
所以现在我们的数据看起来像这样
year office person
1980 President Reagan
1984 President Reagan
1988 President Bush Sr.
1992 President Clinton
1996 President Clinton
2000 President Bush Jr.
2004 President Bush Jr.
2008 President Obama
2012 President Obama
1980 Vice Bush Sr.
1984 Vice Bush Sr.
1988 Vice Quayle
1992 Vice Gore
1996 Vice Gore
2000 Vice Cheney
2004 Vice Cheney
2008 Vice Biden
2012 Vice Biden
现在,至于将办公室和年份“粘合在一起”,我们需要为此使用一点 VBA 函数。在 Access 中创建一个模块,并粘贴以下代码
Public Function ListTerms(person As String) As String
Dim cdb As DAO.Database
Dim rstOffice As DAO.Recordset, rstYear As DAO.Recordset
Dim result As String, yearString As String
Const YearSeparator = ", "
Const OfficeSeparator = "; "
Set cdb = CurrentDb
result = ""
Set rstOffice = cdb.OpenRecordset( _
"SELECT DISTINCT office " & _
"FROM 3_column_data " & _
"WHERE person=""" & Replace(person, """", """""", 1, -1, vbBinaryCompare) & """ " & _
"ORDER BY 1")
Do While Not rstOffice.EOF
yearString = ""
Set rstYear = cdb.OpenRecordset( _
"SELECT DISTINCT [year] " & _
"FROM 3_column_data " & _
"WHERE person=""" & Replace(person, """", """""", 1, -1, vbBinaryCompare) & """ " & _
"AND office=""" & Replace(rstOffice!Office, """", """""", 1, -1, vbBinaryCompare) & """ " & _
"ORDER BY 1")
Do While Not rstYear.EOF
If Len(yearString) > 0 Then
yearString = yearString & YearSeparator
End If
yearString = yearString & rstYear!Year
rstYear.MoveNext
Loop
rstYear.Close
Set rstYear = Nothing
If Len(result) > 0 Then
result = result & OfficeSeparator
End If
result = result & rstOffice!Office & " " & yearString
rstOffice.MoveNext
Loop
rstOffice.Close
Set rstOffice = Nothing
Set cdb = Nothing
ListTerms = result
End Function
现在我们可以在查询中使用该函数来列出每个人及其在办公室的任期
SELECT personlist.[person], ListTerms(personlist.[Person]) as terms
FROM (SELECT DISTINCT person FROM 3_column_data) personlist
返回
person terms
Biden Vice 2008, 2012
Bush Jr. President 2000, 2004
Bush Sr. President 1988; Vice 1980, 1984
Cheney Vice 2000, 2004
Clinton President 1992, 1996
Gore Vice 1992, 1996
Obama President 2008, 2012
Quayle Vice 1988
Reagan President 1980, 1984