Okay, so you're saying it absolutely *MUST* be in a single crosstab query with all that other gunk? Blegh. You people are going to make me master crosstabs if it kills me.
Hmmm. A challenge. Hmmm. That means you're going to need to create at least two different kinds of records... I think it's going to be easiest to break the inner query into three kinds of records, one for the monthly totals, one for counting the first twelve months, and one for counting the second.
Well, the underlying source query needs to be summed at the month level, since that's what we'll end up counting. This inner query will create one record for each month, with the Total of Quantity used. (We're not cutting down the dates yet.) So that will look like this:
Code:
SELECT
TU1.[Part Number],
TU1.[Description],
Format(TU1.[Used Date],"yy/mm") AS UsedYYMM,
Sum(TU1.[Quantity Used]) AS UsedQuant
FROM
[Total Usage] AS TU1
GROUP BY
TU1.[Part Number],
TU1.[Description],
Format(TU1.[Used Date],"yy/mm")
Now, we need three copies of that data, and each copy will then be limited to a date range.
Change your calendar format to this:
Code:
tblCalendar2
Fieldname Field Type
Crossname Text
CrossDate1 Date/Time
CrossDate2 Date/Time
Make three tblCalendar2 records, with this data in them:
Code:
CrossName CrossDate1 CrossDate2
"UsedDate" [Today's Date yy/mm] [25M's End Date yy/mm]
"Months 1-12" [Today's Date yy/mm] [12M's End Date yy/mm]
"Months 13-24" [13M's Start Date yy/mm] [25M's End Date yy/mm]
Later, you could add a fourth record for Months 1-24 if you wanted to, and the code will all work the same.
Finally, paste in this query and run it:
Code:
TRANSFORM Sum(IIF(TC2.CrossName="UsedDate",TU2.UsedQuant,1)) AS TheNumber
SELECT
TU2.[Part Number],
TU2.[Description],
Sum(IIF(TC2.CrossName="UsedDate",TU2.UsedQuant,0)) AS [Sum of Quantity Used]
FROM
tblCalendar2 AS TC2,
(SELECT
TU1.[Part Number],
TU1.[Description],
Format(TU1.[Used Date],"yy/mm") AS UsedYYMM,
Sum(TU1.[Quantity Used]) AS UsedQuant
FROM
[Total Usage] AS TU1
GROUP BY
TU1.[Part Number],
TU1.[Description],
Format(TU1.[Used Date],"yy/mm")
) AS TU2
WHERE
(TU2.UsedYYMM Between TC2.CrossDate1 And TC2.CrossDate2)
GROUP BY
TU2.[Part Number],
TU2.[Description]
Pivot IIF(TC2.Crossname="UsedDate",TU2.UsedYYMM,TC2.CrossName);
The sample output looks good, so that should work for you.
Explanation:
The Pivot will splay out each month's data, leaving two final columns for the monthly counts.
The Transform will sum up the totals, which will only matter in the case of the two monthly counts, since we already grouped the selected records by month in the inner query.
In each case, the records will be limited to the dates requested in the tblCalendar records.
Note that the sum column in the SELECT is slightly different than the sum column in the transform, to avoid adding a count of months to the sums of actual usage numbers.