我想添加这个表达式:
([2013]/[2012]-1) AS [Change%]
作为以下交叉表查询的字段:
TRANSFORM
Sum(Data.Spending)
SELECT
Data.Category
FROM
Data
WHERE
(((Data.Year)="2012" Or (Data.Year)="2013"))
GROUP BY
Data.Category
PIVOT
Data.Year;
这是通过使用此主题中的另一个表来解决的:Access 2007 Crosstab Query Expression
但是出于我的目的,我需要在一个查询中将所有内容放在一起。
这是因为我在另一个程序http://www.ljzsoft.com/ppt-report.htm中编写SQL,它使用查询直接访问Access数据库。
答案 0 :(得分:0)
正如您可能已经发现的那样,Access不允许我们将Crosstab查询用作子查询。如果我们尝试做
SELECT ...
FROM
(
TRANSFORM
我们得到“FROM子句中的语法错误”。一种解决方法是执行所有聚合,创建派生(计算)值,将它们组合在一起,然后“交叉”。在你的情况下:
TRANSFORM Sum(ColValue) AS SumOfColValue
SELECT Category
FROM
(
SELECT Category, [Year] AS ColHead, Sum(Spending) AS ColValue
FROM Data
WHERE [Year] IN ("2012", "2013")
GROUP BY Category, [Year]
UNION ALL
SELECT
curr.Category,
"Change%" AS ColHead,
(curr.SumOfSpending/prev.SumOfSpending-1) AS ColValue
FROM
(
SELECT Category, [Year], Sum(Spending) AS SumOfSpending
FROM Data
WHERE [Year] IN ("2012", "2013")
GROUP BY Category, [Year]
) AS curr
INNER JOIN
(
SELECT Category, [Year], Sum(Spending) AS SumOfSpending
FROM Data
WHERE [Year] IN ("2012", "2013")
GROUP BY Category, [Year]
) AS prev
ON prev.Category = curr.Category
AND CLng(prev.[Year]) = (CLng(curr.[Year]) - 1)
)
GROUP BY Category
PIVOT ColHead
,对于我的样本数据,返回
Category 2012 2013 Change%
--------- ---- ---- -----------------
Category1 123 345 1.80487804878049
Category2 234 456 0.948717948717949
如果您对自己的喜好太过讨厌,那么您可能需要调查您的报告工具是否支持计算的报告字段(例如,在Crystal Reports中我认为它们被称为“公式字段”)。