So, I tried to change the last inner join:
INNER JOIN mdl_groups AS g ON gm.groupid = g.id AND c.id = g.courseid
BUT, if a course doesn't have groups, the query results zero record ...
INNER JOIN mdl_groups AS g ON gm.groupid = g.id AND c.id = g.courseid
BUT, if a course doesn't have groups, the query results zero record ...