Question : Query containg subquery as source for crosstab

I have a table called DispatchLog with DispatchID and Dispatch_Date.

I made a query called "DispatchSheetDataQuery" to produces a list of all dispatch dates, with a rank column numbered sequentially, restarting at 1 for every new date:

SELECT DISPATCHLOG.dispatch_date, DISPATCHLOG.Dispatch_Id, (SELECT Count(Dispatch_Id)
      FROM DISPATCHLOG AS t2
      WHERE t2.dispatch_date = DISPATCHLOG.dispatch_date
      AND t2.Dispatch_Id <= DISPATCHLOG.Dispatch_Id
) AS Rank
FROM DISPATCHLOG
ORDER BY DISPATCHLOG.dispatch_date, DISPATCHLOG.Dispatch_Id;

I should be able to use this calculated "Rank" column as the RowHeader, and the DispatchDate column as the Column header, with DispatchID as the value in a crosstab.

Every attempt to do so produces:

The Microsoft Office Access database engine does not recognize 'DISPATCHLOG.dispatch_date' as a valid field name or expression.

My crosstab looks like this:

TRANSFORM First(DispatchSheetDataQuery.Dispatch_Id) AS FirstOfDispatch_Id
SELECT DispatchSheetDataQuery.Rank
FROM DispatchSheetDataQuery
GROUP BY DispatchSheetDataQuery.Rank
PIVOT DispatchSheetDataQuery.dispatch_date;

Answer : Query containg subquery as source for crosstab

You are right, Jet gets very confused when trying to optimise this query. In fact, it's not the field "dispatch_date" that causes the problem, but the rank.

If you change your first query to a make-table query, you can then base the cross-tab on the temporary table. If needed, you can also add indexes to the temporary table:

    CREATE INDEX ndxDate ON TempTable (dispatch_date);

While I'm at it, your query runs about 20 times faster with an index on dispatch_date (on the main table DISPATCHLOG that is).

Other solutions would be to get the 'rank' field back into the main table (one more query), or to create the ranks through a Visual Basic loop -- it would be just as fast.

(°v°)
Random Solutions  
 
programming4us programming4us