1

I have the following query which works fine:

SELECT *, COUNT(*) FROM attendance, cohort 
WHERE 
attendance.cohort_fk = cohort.cohort_pk 
AND 
attendance.cohort_fk = '$cohort' 
AND 
YEAR(attendance.attended) = '$year'
GROUP BY attendance.person_id ASC

In the table cohort, there is an int column 'attendance_pass'. Now I want to have another query similar to above that only returns records where COUNT(*) FROM attendance equals cohort.attendance_pass. Eg.

SELECT *, COUNT(*) FROM attendance, cohort 
WHERE 
attendance.cohort_fk = cohort.cohort_pk 
AND 
attendance.cohort_fk = '$cohort' 
AND 
YEAR(attendance.attended) = '$year'
AND 
COUNT() = cohort.attendance_pass
GROUP BY attendance.person_id ASC

How can I modify this second query to get just those records?

2 Answers 2

1

You need to use HAVING

SELECT *, COUNT(*) FROM attendance, cohort 
WHERE 
attendance.cohort_fk = cohort.cohort_pk 
AND 
attendance.cohort_fk = '$cohort' 
AND 
YEAR(attendance.attended) = '$year'

GROUP BY attendance.person_id ASC

HAVING COUNT(*) = cohort.attendance_pass
Sign up to request clarification or add additional context in comments.

Comments

1

the aggregation functions must be in an having clause, not in the where clause.

By the way, you can use the alias.

And I don't think you can GROUP BY asc, you certainly mean a GROUP BY then an ORDER BY ... ASC

select *, count(*) as cnt from attendance
-- etc.

where
--etc.
having cnt = cohort.attendance_pass
GROUP BY attendance.person_id
ORDER BY attendance.person_id ASC

1 Comment

I had a problem with 'as cnt' returning "Unknown column 'attendance.cohort_fk' in 'where clause'"....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.