sql - Single query to count by category by joining multiple tables -
i have following 3 tables. write single query count of number of courses enrolled in student every difficulty level, , total number of courses enrolled in well. students have not enrolled should listed too.
students table: student id student name 1 alice 2 bob 3 charlie 4 david courses table: course id course name difficulty level 1 arithmetic 1 2 advanced calculus 3 3 algebra 2 4 trignometry 2 enrollment table: enrollment id student id course id 1 1 1 2 1 3 3 1 4 4 2 2 5 2 3 6 2 4 7 3 3
here's expected output:
output: student id student name total courses courses courses courses enrolled in difficulty level 1 difficulty level 2 difficulty level 3 1 alice 3 1 2 0 2 bob 3 0 2 1 3 charlie 1 0 1 0 4 david 0 0 0 0
i appreciate this. i've tried few different queries , finding hard arrive @ single query lists students.
select s.[student id] , s.[student name] , count(c.[course id]) , count(case when c.[difficulty level] = 1 end) , count(case when c.[difficulty level] = 2 end) , count(case when c.[difficulty level] = 3 end) students s left join enrollment e on e.[student id] = s.[student id] left join courses c on c.[course id] = e.[course id] group s.[student id] , s.[student name]
Comments
Post a Comment