我一直在尝试使用VBA Access中的TRANSFORM SQL创建表。但是,我希望我的Pivot Key(Top行)值不是基于字母顺序而是手动排序。 这是我的SQL代码:
TRANSFORM Count(*) AS [Count]
SELECT MyQry.Period
FROM MyQry
WHERE ((MyQry.[Code]) ='A1' Or (MyQry.[Code])='A3' Or (MyQry.[Code])='A6' Or (MyQry.[Code])='A7' Or (MyQry.[Code])='A4')
GROUP BY MyQry.Period
ORDER BY MyQry.Period
PIVOT MyQry.[Code];
它给我一张表如下:
Period A1 A3 A6 A7 A4
2015 5 10 8 9 0
2014 10 8 9 6 2
... . . . . .
但是,我想要的是一个具有相同句点和值的表,但表列值的排序如下:
Period A1 A3 A4 A6 A7
2015 5 10 0 8 9
2014 10 8 2 9 6
... . . . . .
然后我想将列名更改为:
Period Primary Secondary Code Code A4 Code A6 Code A7
2015 5 10 0 8 9
2014 10 8 2 9 6
... . . . . .
由于
答案 0 :(得分:1)
您可以在pivot子句中使用条件表达式来更改列标题,如下所示:
TRANSFORM Count(*) AS [Count]
SELECT MyQry.Period
FROM MyQry
GROUP BY MyQry.Period
PIVOT
IIf([Code]='A1',"Primary Code",
IIf([Code]='A3',"Secondary Code",
IIf([Code]='A4',"Code A4",
IIf([Code]='A6',"Code A6",
IIf([Code]='A7',"Code A7","")))));
但列的顺序仍然是按字母顺序排列的。您的代码当然会将列标题更改为按所需顺序对列进行排序的内容(例如" 1.主要"," 2.。中等"," 4。代码A4"等),但这会以可能不需要的方式更改列名称。
另一个,在我看来更好的选择是完全跳过转换/转换,而是使用条件表达式和count聚合函数,如下所示:
SELECT
Period,
COUNT(IIF(Code='A1', Code, null)) AS [Primary Code],
COUNT(IIF(Code='A3', Code, null)) AS [Secondary Code],
COUNT(IIF(Code='A4', Code, null)) AS [Code A4],
COUNT(IIF(Code='A6', Code, null)) AS [Code A6],
COUNT(IIF(Code='A7', Code, null)) AS [Code A7]
FROM MyQry
GROUP BY Period
ORDER BY Period;
这可以为您提供您想要的内容,并且可以更好地控制输出。