Question

I have two tables: TblA TargetDate and TblB DepartmentName

The two tables are joined using a composite key which consists of four fields: RecNr, DiarieNr, ReportMonth, ReportYear

TblA
RecNr,  DiarieNr, ReportMonth, ReportYear, TargetDate,  DepartmentName
1       1000      7            2013        01/08/2013   DeptA
2       1000      7            2013        01/10/2013   DeptA
3       1000      7            2013        01/08/2013   DeptC
1       3000      7            2013        01/07/2013   DeptB
2       3000      7            2013        01/09/2013   DeptB
3       3000      7            2013        01/01/2014   DeptA

TblB
RecNr,  DiarieNr, ReportMonth, ReportYear, Completed
1       1000      7            2013        2013
2       1000      7            2013        2013
3       1000      7            2013        2013
1       3000      7            2013        2013
2       3000      7            2013        2012
3       3000      7            2013        2013

Now - I need to create a summary of the Median for each Department for entries that were completed in 2013, like this:

Department Name     TargetDate
DeptA               01/10/2013
DeptB               01/07/2013
DeptC               01/08/2013

My best and only guess to do this is like the query below, but when I run the sql in Access I'm prompted to provide a DepartmentName. So I guess that it's not referenced properly from the main query.

SELECT DISTINCT A.DepartmentName,
(SELECT TOP 1 TargetDate 
  FROM (
       SELECT TOP 50 PERCENT TargetDate 
         FROM TblA A1  
        WHERE DepartmentName=A2.DepartmentName 
        ORDER BY A1.DepartmentName
   ) AS A2 
  WHERE A.DepartmentName=A2.DepartmentName 
  ORDER BY TargetDate
 )
FROM TblB M 
INNER JOIN TblA A ON M.ReportMonth=A.ReportMonth 
    AND M.ReportYear=A.ReportYear 
    AND M.DiarieNr=A.DiarieNr 
    AND M.RecNr=A.RecNr
WHERE A.DepartmentName<>'' AND YEAR(TblB.Completed)=2013
Was it helpful?

Solution

When you want to use the alias of a table, the correct syntax is: FROM TblB As M

You missed out the AS

You would be better off using the Ms Access query designer which would automatically generate the correct syntax.

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