使用MS Access我有两个交叉表查询,总结了我的数据。一个按位置和财政季度获得数据行总数;另一个查询得到符合地点和财政季度标准的百分比。
以下示例(为了解决问题,它们已经过简化)。
Location Period CountIt
Blue FY13-Q3 Yes
Orange FY13-Q1 No
Blue FY14-Q1 No
Orange FY13-Q1 Yes
然后我有一个交叉表,它从Yes
列中获取CountIt
值的百分比,另一个显示每个会计季度的总计数。
TRANSFORM Sum(IIf(qryA.CountIt Like "Yes",1,0))/Count(qryA.CountIt) AS PercentYes
SELECT qryA.[Location]
FROM qryA
GROUP BY qryA.[Location]
PIVOT qryA.[Period];
## Crosstab Output
Location FY13-Q1 FY13-Q2 FY13-Q3 FY13-Q4 FY14-Q1
Blue 12% 15% 13.2% 19% 15%
Orange 9% 12% 1% 18% 12%
TRANSFORM Count(qryA.CountIt) AS FiscalCount
SELECT qryA.[Location]
FROM qryA
GROUP BY qryA.[Location]
PIVOT qryA.[Period];
## Crosstab that display total count by location and Fiscal quarter
Location FY13-Q1 FY13-Q2 FY13-Q3 FY13-Q4 FY14-Q1
Blue 102 111 54 124 122
Orange 91 321 122 158 129
我想创建一个组合表,显示“是”的百分比和总计数
FY13-Q1 FY13-Q2 FY13-Q3 FY13-Q4 FY14-Q1
Location Per% Tot Per% Tot Per% Tot Per% Tot Per% Tot
Blue 12% 102 15% 111 13.2% 54 19% 124 15% 122
Orange 9% 91 12% 321 1% 122 18% 158 12% 129
这可能吗?正如您所看到的,我的行标题是会计期间,随着我添加更多数据,我将获得更多行(它们是动态的)...我不确定如何将这些行合并到期望结果中。
谢谢!
答案 0 :(得分:5)
截至2013财年第一季度,2013财年第二季度,2013财年第三季度,第13季度至第四季度,2014财年第一季度似乎是一个综合列表,您可以使用IN
TRANSFORM Sum(aTable.aNumber) AS SumOfaNumber
SELECT aTable.aText, Sum(aTable.aNumber) AS [Total Of aNumber]
FROM aTable
GROUP BY aTable.aText
PIVOT "FY" & Format(ADate,"yy") & "-Q" & Format([ADate],"q")
In ("FY13-Q1","FY13-Q2","FY13-Q3","FY13-Q4","FY14-Q1");
您可以使用查询设计窗口中的列标题属性添加标题,或者只需键入SQL视图窗口。
请注意,如果省略值IN表格,即使有数据,列也不会显示。
如果您在VBA中构建查询,您可以更改标题列表以适合您希望使用的季度,或者省略格式化(FY13-01等),因此MS Access返回Qtr 1,Qtr 2等< / p>
然后,您可以加入适合的数据:
SELECT atable_crosstab.[FY13-Q1],
atable_crosstab2.[FY13-Q1] AS [Per Q1],
atable_crosstab.[FY13-Q2],
atable_crosstab2.[FY13-Q2] AS [Per Q2],
atable_crosstab.[FY13-Q3],
atable_crosstab2.[FY13-Q3] AS [Per Q3],
atable_crosstab.[FY13-Q4],
atable_crosstab2.[FY13-Q4] AS [Per Q4]
FROM atable_crosstab
INNER JOIN atable_crosstab2
ON atable_crosstab.atext = atable_crosstab2.atext;
但是,您将无法拥有跨两列的标头。
这是VBA中的草图
Sub BuildCrosstab()
Dim sBase As String
Dim iQtr, iYear, iStartYear, iEndYear
Dim sIn As String
Dim CurDate As Date
Dim qdf As QueryDef
sBase = "TRANSFORM Sum(aTable.aNumber) AS SumOfaNumber " _
& "SELECT aTable.aText, Sum(aTable.aNumber) AS [Total Of aNumber] " _
& "FROM aTable " _
& "GROUP BY aTable.aText " _
& "PIVOT ""FY"" & Format(ADate,""yy"") & ""-Q"" & Format([ADate],""q"") In "
iStartYear = Year(Date) - 1
iEndYear = Year(Date)
For iYear = iStartYear To iEndYear
CurDate = DateSerial(iYear, 1, 1)
For iQtr = 1 To 4
If CurDate <= Date Then
sIn = sIn & ",""" & "FY" & Format(CurDate, "yy") & "-Q" _
& Format(CurDate, "q") & """"
CurDate = DateAdd("q", 1, CurDate)
End If
Next
Next
sIn = "(" & Mid(sIn, 2) & ")"
''This query exists
Set qdf = CurrentDb.QueryDefs("ATable_Crosstab")
qdf.SQL = sBase & sIn
End Sub