Question

I would like to add this expression:

([2013]/[2012]-1) AS [Change%]

As a field to the crosstab query below:

TRANSFORM 
      Sum(Data.Spending)
SELECT 
      Data.Category
FROM
      Data
WHERE 
      (((Data.Year)="2012" Or (Data.Year)="2013"))
GROUP BY 
     Data.Category
PIVOT 
     Data.Year;

This is solved through using another table in this thread: Access 2007 Crosstab Query Expression

But for my purposes I need to have everything together in one query.

This is because I am writing SQL in another program, http://www.ljzsoft.com/ppt-report.htm, which uses the query to directly access an Access database.

Was it helpful?

Solution

As you have probably discovered, Access won't let us use a Crosstab query as a subquery. If we try to do

SELECT ...
FROM
    (
        TRANSFORM

we get "Syntax error in FROM clause". One workaround is to do all of the aggregations, create the derived (calculated) values, UNION them together, and then "crosstab" that. In your case:

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

which, for my sample data, returns

Category   2012  2013  Change%          
---------  ----  ----  -----------------
Category1   123   345   1.80487804878049
Category2   234   456  0.948717948717949

If that is too nasty for your liking then you might want to investigate whether your reporting tool supports calculated report fields (e.g., in Crystal Reports I believe they are called "Formula Fields").

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top