Assuming that your database had been properly normalized, where each blood sample had a unique record, then the answer would be pretty simple. This will average the values for a year:
Code:
tlbEmployees
EmpID
EmpLName
EmpFName
EmpMI
EmpSSN
EmpDept
tlbSamples
SampPK Autokey
SampEmpID FK to EmpID
SampDt Date
SampPB Number
SELECT SampEmpID, Count(SampDt), Avg(SampPB)
FROM tblSamples
WHERE SampDate Between DateAdd("d",1,DateAdd("yyyy",-1,Date)) AND Date
GROUP BY SampEmpID;
On the other hand, since your samples are laid out in a single unnormalized record that holds twelve months, then you have a more complicated problem, especially if you want to do a year (including records for Nov and Dec of last year).
Here's the simple, each-year-only version:
Code:
Query:
SELECT
SampYear,
SampEmpID,
SampCountPB,
SampSumPB,
SampSumPB/IIF(SampCountPB>0,SampCountPB,1) AS AvgPB
FROM
(SELECT SampYear, SampEmpID.
IIF(SampPBJan>0,1,0) + IIF(SampPBFeb>0,1,0) +
IIF(SampPBMar>0,1,0) + IIF(SampPBApr>0,1,0) +
IIF(SampPBMay>0,1,0) + IIF(SampPBJun>0,1,0) +
IIF(SampPBJul>0,1,0) + IIF(SampPBAug>0,1,0) +
IIF(SampPBSep>0,1,0) + IIF(SampPBOct>0,1,0) +
IIF(SampPBNov>0,1,0) + IIF(SampPBDec>0,1,0) AS SampCountPB,
SampPBJan + SampPBFeb + SampPBMar +
SampPBApr + SampPBMay + SampPBJun +
SampPBJul + SampPBAug + SampPBSep +
SampPBOct + SampPBNov + SampPBDec AS SampSumPB
FROM tblSamples);
With your current structure, to get a running year, you'd need to replace each of the twelve terms in the year-only query like this:
replace "IIF(SampPBJan>0,1,0)" in the SampCountPB calculation with
Code:
IIF(DateSerial(SampYear,01,01)<=DateAdd("yyyy",-1,Date),0,
IIF(DateSerial(SampYear,01,01)>Date),0,
IIF(SampPBJan>0,1,0)))
and replace "SampPBJan" in the SampSumPB calculation with
Code:
IIF(DateSerial(SampYear,01,01)<=DateAdd("yyyy",-1,Date),0,
IIF(DateSerial(SampYear,01,01)>Date),0,SampPBJan)
Technically, the Dateserial()>Date isn't needed when you're using current date to determine the one-year, but I've included it so that if you wanted one-year-back from some prior date, the code would work.
The final query would look something like this...assuming it fits in the limit of number of characters for a query...
Code:
Query:
SELECT
SampEmpID,
SUM(SampCountPB),
SUM(SampSumPB),
SUM(SampSumPB)/IIF(SUM(SampCountPB)>0,SUM(SampCountPB),1) AS AvgPB
FROM
(SELECT SampYear, SampEmpID.
IIF(DateSerial(SampYear,01,01)<=DateAdd("yyyy",-1,Date),0,
IIF(DateSerial(SampYear,01,01)>Date),0,
IIF(SampPBJan>0,1,0))) +
IIF(DateSerial(SampYear,02,01)<=DateAdd("yyyy",-1,Date),0,
IIF(DateSerial(SampYear,02,01)>Date),0,
IIF(SampPBFeb>0,1,0))) +
(...repeat for other ten months...)
AS SampCountPB,
IIF(DateSerial(SampYear,01,01)<=DateAdd("yyyy",-1,Date),0,
IIF(DateSerial(SampYear,01,01)>Date),0,SampPBJan) +
IIF(DateSerial(SampYear,02,01)<=DateAdd("yyyy",-1,Date),0,
IIF(DateSerial(SampYear,02,01)>Date),0,SampPBFeb) +
(...repeat for other ten months...)
AS SampSumPB,
FROM tblSamples)
GROUP BY SampEmpID;