Access 2016中的转换和数据透视

时间:2018-10-29 14:52:54

标签: sql ms-access

我知道这方面有一些话题,但是所有示例均与我需要完成的工作背道而驰。

我在Access 2016中有如下数据:

Source Data

我需要垂直旋转它,使其看起来像这样:

Preferred Output

等等学生ID栏永远不会改变,但是问题的数量不会改变,因此我认为在记录结束之前它必须是某种循环。

Powerquery在excel中很容易做到这一点,但是我需要它在访问中是本机的。

或者,如果有人可以向后解释如何TRANSFORM and PIVOT in Access 2013 SQL,我也许可以从那里完成。

正常的枢轴和取消枢轴将无法处理此问题,因为我需要将列标题作为数据字段下移,并且我需要它循环此移动直到记录结束,并且不知道确切多少每次都会有列。因此,文件可能一次转到Q07,另一次转到Q43。

我具有访问权限的技能水平是业余水平。我可以做足够的VBA复制和修改代码,但不足以在Access中编写代码。

谢谢您的协助!

2 个答案:

答案 0 :(得分:1)

您只需使用union all

select studentId, 'Q01' as question, q01 as response
from data
union all
select studentId, 'Q02' as question, q02 as response
from data
union all
. . .

答案 1 :(得分:0)

首先我尝试了这个。

SELECT StudentID, [Questionnaire #] as QuestionnaireID, 'Q01' as Question, [Q01] as Response FROM Random_data_generator UNION ALL
SELECT StudentID, [Questionnaire #] as QuestionnaireID, 'Q02' as Question, [Q02] as Response FROM Random_data_generator UNION ALL
SELECT StudentID, [Questionnaire #] as QuestionnaireID, 'Q03' as Question, [Q03] as Response FROM Random_data_generator UNION ALL
SELECT StudentID, [Questionnaire #] as QuestionnaireID, 'Q04' as Question, [Q04] as Response FROM Random_data_generator UNION ALL
SELECT StudentID, [Questionnaire #] as QuestionnaireID, 'Q05' as Question, [Q05] as Response FROM Random_data_generator UNION ALL
SELECT StudentID, [Questionnaire #] as QuestionnaireID, 'Q06' as Question, [Q06] as Response FROM Random_data_generator UNION ALL
SELECT StudentID, [Questionnaire #] as QuestionnaireID, 'Q07' as Question, [Q07] as Response FROM Random_data_generator
ORDER BY StudentID, Question;

但是我不知道如何为随机数的答案动态地做到这一点。所以我吹走了我VB书籍上的灰尘,最后得到了这个,我敢肯定它的编码不好,会让人们畏缩。但是可以。

Dim db As DAO.Database
Set db = CurrentDb
Dim qdf As DAO.QueryDef

ColumnCount = CurrentDb.TableDefs("Random_data_generator").Fields.Count
ColumnCount2 = ColumnCount - 2
Dim QueryString As String
Dim QueryEntry As String
Dim counter As Integer
Dim counterEntry As String
Dim QueryTest As Recordset
Dim QuestionnaireNum As String
counter = 1


Do While counter <= ColumnCount2

 counterEntry = Format(counter, "00")

    QueryString = "SELECT StudentID, [QuestionnaireNum] as QuestionnaireID, 'Q" & counterEntry & "' as Question, [Q" & counterEntry & "] as Response FROM Random_data_generator UNION ALL " & vbCrLf
    counter = counter + 1
    QueryEntry = QueryEntry + QueryString

 Loop

 counterEntry = Format(counter, "00")

 QueryString = "SELECT StudentID, [QuestionnaireNum] as QuestionnaireID, 'Q" & counterEntry & "' as Question, [Q" & counterEntry & "] as Response FROM Random_data_generator ORDER BY StudentID, Question;"
 QueryEntry = QueryEntry + QueryString

 On Error Resume Next
 DoCmd.DeleteObject acQuery, "tempQry"
 On Error GoTo 0

 Set qdf = db.CreateQueryDef("tempQry", QueryEntry)

 DoCmd.OpenQuery ("tempQry")