I have a table “rota” where volunteers submit the shifts they are available. They can submit more than 6 shifts, but 6 is the minimum required.
I want to see how many volunteers have selected each of the shifts, but I want to see only those who have selected 6 shifts.
I am running a wrong SQL, but can-t figure it out what I am doing wrong:
SELECT COUNT(volunteer_id), shift_id
FROM rota
GROUP BY shift_id
WHERE COUNT(shift_id = 6);
EDIT:
I wrongly explained what I was trying to do.
I want to see how many volunteers have selected each of the shifts, but I want to see only those shifts who have been selected by volunteers who submitted only 6 shifts. Does it make sense?
EDIT:
Tried this but not working:
SELECT COUNT(volunteer_id), shift_id
FROM rota
WHERE volunteer_id IN (SELECT volunteer_id FROM rota
GROUP BY volunteer_id HAVING COUNT DISTINCT(shift_id) = 6)
GROUP BY shift_id;
2
Answers
You can try below –
Use a
HAVING
clause:Assertions which take place after
GROUP BY
has happened need to appear in aHAVING
clause.HAVING
operates on groups of records. TheWHERE
clause, on the other hand, is evaluated beforeGROUP BY
, and operates on individual records.