views:

472

answers:

2

In MS Access, I have a query where I want to use a column in the outer query as a condition in the inner query:

SELECT P.FirstName, P.LastName, Count(A.attendance_date) AS CountOfattendance_date,
       First(A.attendance_date) AS FirstOfattendance_date,
       (SELECT COUNT (*) 
          FROM(SELECT DISTINCT attendance_date 
                FROM tblEventAttendance AS B 
                WHERE B.event_id=8 
                  AND B.attendance_date >= FirstOfattendance_date)
       ) AS total
FROM tblPeople AS P INNER JOIN tblEventAttendance AS A ON P.ID = A.people_id
WHERE A.event_id=8
GROUP BY P.FirstName, P.LastName
;

The key point is FirstOfattendance_date - I want the comparison deep in the subselect to use the value in each iteration of the master select. Obviously this doesn't work, it asks me for the value of FirstOfattendance_date when I try to run it.

I'd like to do this without resorting to VB code... any ideas?

A: 

Can you change

B.attendance_date >= FirstOfattendance_date

to

B.attendance_date >= First(A.attendance_date)

interesting, but then it says you cannot have an aggregate function in a where clause.
DGM
An aggregate functions can be used as criteria only in the HAVING clause. Since you're using the value from the aggregate correlated subquery, you have to use the alias, as the SELECT statement you're using it in is not an aggregate query.
David-W-Fenton
+1  A: 

How about:

SELECT 
     p.FirstName,
     p.LastName,
     Count(a.attendance_date) AS CountOfattendance_date,
     First(a.attendance_date) AS FirstOfattendance_date,
     c.total
FROM (
     tblPeople AS p 
INNER JOIN tblEventAttendance AS a ON 
     a.people_id = p.ID) 
INNER JOIN (SELECT people_id, Count (attendance_date) As total
            FROM (
                SELECT DISTINCT people_id,attendance_date
                FROM tblEventAttendance) 
            Group By people_id) AS c ON 
     p.ID = c.people_id
GROUP BY 
     p.ID, c.total;
Remou
That may be getting closer, but it lost the event_id=8 part, and a distinct search for possible dates. But I think this is on the right track, putting the sub select logic in the from area instead of the select area.
DGM