Here is a more generalized query that also gets the other counts on the Canvas Analytics page. This query is meant mostly to be instructive and is not necessarily a best practice. It would probably perform better if it were broken in to several smaller queries. However, this query should match the logic in the Canvas Analytics subaccount page. I did some spot checking and things seem to line up, however, I would be interested to know if anyone finds any discrepancies.
select
et.name,
a.subaccount1,
count(distinct c.id) as course_count,
count(distinct enroll_student.user_id) as enrolled_user_count,
count(distinct enroll_teach.user_id) as enrolled_teacher_count,
count(distinct dtd.id) discussion_topic_count,
count(distinct assn.id) assignment_count
from (
select distinct
a.id as account_id,
cx.id as course_id
from account_dim a
inner join course_dim c on c.account_id = a.id
inner join course_section_dim cs on cs.nonxlist_course_id = c.id
inner join course_dim cx on cx.id = cs.course_id
union
select distinct
a.id as account_id,
c.id as course_id
from account_dim a
inner join course_dim c on c.account_id = a.id
) acct_course
inner join account_dim a on a.id = acct_course.account_id
inner join course_dim c on c.id = acct_course.course_id
inner join enrollment_term_dim et on et.id = c.enrollment_term_id
left outer join (
select ef.user_id, ef.course_id
from enrollment_dim ed
inner join enrollment_fact ef on ef.enrollment_id = ed.id and (ed.workflow_state='active' or ed.workflow_state='completed') and ed.type='TeacherEnrollment'
) enroll_teach on enroll_teach.course_id=acct_course.course_id
left outer join (
select ef.user_id, ef.course_id
from enrollment_dim ed
inner join enrollment_fact ef on ef.enrollment_id = ed.id and (ed.workflow_state='active' or ed.workflow_state='completed') and ed.type='StudentEnrollment'
) enroll_student on enroll_student.course_id=acct_course.course_id
left outer join assignment_dim assn on assn.course_id = acct_course.course_id and assn.workflow_state = 'published'
left outer join discussion_topic_fact dtf on dtf.course_id = acct_course.course_id
left outer join discussion_topic_dim dtd on dtd.id = dtf.discussion_topic_id and dtd.workflow_state != 'deleted'
where
(c.workflow_state = 'available' or c.workflow_state = 'completed' )
group by et.id, et.name,et.date_start,2
order by et.date_start,et.name,2
This discussion post is outdated and has been archived. Please use the Community question forums and official documentation for the most current and accurate information.