The error says it all, you're not grouping by MEMBERS.MEMBER_ID
and MEMBERS.MEMBER_NAME
.
SELECT MEMBERS.MEMBER_ID, MEMBERS.MEMBER_NAME
, COUNT(personal_training_sessions.session_id)
FROM MEMBERS
JOIN personal_training_sessions
ON personal_training_sessions.member_id = members.member_id
GROUP BY MEMBERS.MEMBER_ID, MEMBERS.MEMBER_NAME
You want the count of personal sessions per member, so you need to group by the member information.
The basic (of course it can get a lot more complex) GROUP BY, SELECT query is:
SELECT <column 1>, <column n>
, <aggregate function 1>, <aggregate function n>
FROM <table_name>
GROUP BY <column 1>, <column n>
An aggregate function being, as Ken White says, something like MIN()
, MAX()
, COUNT()
etc. You GROUP BY all the columns that are not aggregated.
This will only work as intended if your MEMBERS
table is unique on MEMBER_ID
, but based on your query I suspect it is. To clarify what I mean, if your table is not unique on MEMBER_ID
then you're not counting the number of sessions per MEMBER_ID
but the number of sessions per MEMBER_ID
and per MEMBER_NAME
. If they're in a 1:1 relationship then it's effectively the same thing but if you can have multiple MEMBER_NAME
s per MEMBER_ID
then it's not.