Professional Documents
Culture Documents
An example
A crosstab query is a matrix, where the column headings come from the values in a field. In the
example below, the product names appear down the left, the employee names become fields, and
the intersection shows how many of this product has been sold by this employee:
To create this query, open the Northwind sample database, create a new query, switch to SQL View
(View menu), and paste:
TRANSFORM Sum([Order Details].Quantity) AS SumOfQuantity
SELECT Products.ProductID, Products.ProductName, Sum([Order
Details].Quantity) AS Total
FROM Employees INNER JOIN (Products INNER JOIN (Orders INNER JOIN [Order
Details]
ON Orders.OrderID = [Order Details].OrderID)
ON Products.ProductID = [Order Details].ProductID)
ON Employees.EmployeeID = Orders.EmployeeID
GROUP BY Products.ProductID, Products.ProductName
PIVOT [Employees].[LastName] & ", " & [Employees].[FirstName];
In Access 2007 and later, you can also show the total at the bottom of each column, by depressing
the Totals button on the ribbon. The button is on the Records group of the Home tab, and the icon
is an upper case sigma ().
Handle parameters
A query can ask you to supply a value at runtime. It pops up a parameter dialog if you enter
something like this:
[What order date]
Or, it can read a value from a control on a form:
[Forms].[Form1].[StartDate]
But, parameters do not work with crosstab queries, unless you:
a) Declare the parameter, or
b) Specify the column headings.
To declare the parameter, choose Parameters on the Query menu. Access opens a dialog. Enter the
name and specify the data type. For the examples above, use the Query Parameters dialog like this:
Parameter
Data Type
Date/Time
[Forms].[Form1].[StartDate]
Date/Time
OK
[ Cancel ]
Declaring your parameters is always a good idea (except for an Access bug in handling parameters
of type Text), but it is not essential if you specify your column headings.
For the query above, set the Column Headings property like this (on one line):
"Buchanan, Steven", "Callahan, Laura", "Davolio, Nancy", "Dodsworth, Anne", "Fuller, Andrew", "King,
Robert", "Leverling, Janet", "Peacock, Margaret", "Suyama, Michael"
Side effects of using column headings:
Any values you do not list are excluded from the query.
The fields will appear in the order you specify, e.g. "Jan", "Feb", "Mar", ...
Where a report has a complex crosstab query as its Record Source, specifying the column headings
can speed up the design of the report enormously. If you do not specify the column headings,
Access is unable to determine the fields that will be available to the report without running the
entire query. But if you specify the Column Headings, it can read the field names without running
the query.
An alternative approach is to alias the fields so the names don't change. Duane Hookom has an
example of dynamic monthly crosstab reports.
It generates fields named Amt and the month number, and Qty and the month number: