 SELECT ue.id,
                                      u.id AS userid,u.firstnamephonetic,u.lastnamephonetic,u.middlename,u.alternatename,u.firstname,u.lastname, u.email,

                                      c.id AS courseid,
                                      c.fullname,
                                      ue.timecreated,

                                      IFNULL((SELECT COUNT(gg.finalgrade)
                                        FROM {grade_grades}  gg
                                        JOIN {grade_items}  gi ON gg.itemid=gi.id
                                        WHERE gi.courseid=c.id
                                         AND gg.userid=u.id
                                         AND gi.itemtype='mod'
                                         GROUP BY u.id,c.id),'0') AS 'activities_completed',

                                      IFNULL((SELECT COUNT( gi.itemname )
                                        FROM {grade_items}  gi
                                        WHERE gi.courseid = c.id
                                         AND gi.itemtype='mod'), '0') AS 'activities_assigned',

                                      (
                                          SELECT IF(activities_assigned!='0', (
                                              SELECT IF( activities_completed = activities_assigned,
                                              (
                                                  SELECT CONCAT('100% completo',FROM_UNIXTIME(MAX(log.time),'%m/%d/%Y'))
                                                    FROM {log} log
                                                   WHERE log.course = c.id
                                                     AND log.userid = u.id
                                              ),
                                              (
                                                  SELECT CONCAT(IFNULL(ROUND((activities_completed)/(activities_assigned)*100,0),
                                                        '0'),'% complete')))), 'n/a')
                                      ) AS 'course_completed'

                                    FROM {user} u
                                    JOIN {user_enrolments}  ue  ON ue.userid = u.id
                                    JOIN {enrol}            e   ON e.id = ue.enrolid
                                    JOIN {course}           c   ON c.id = e.courseid
                                    JOIN {context}          ctx ON ctx.instanceid = c.id AND ctx.instanceid = c.id
                                    JOIN {role_assignments} ra  ON ra.contextid = ctx.id AND ra.userid = u.id
                                    JOIN {role}             r   ON r.id = e.roleid

                                    WHERE ra.roleid = 5
                                      AND c.id      = :courseid
                                  GROUP BY u.id, c.id