-1

次の3つのテーブルがあります。難易度ごとに学生が登録したコースの数と、登録したコースの総数を取得する単一のクエリを作成したいと思います。登録していない学生もリストに記載する必要があります。

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

予想される出力は次のとおりです。

Output:
Student ID      Student Name    Total Courses       Courses with        Courses with        Courses with
                                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

これについて何か助けていただければ幸いです。いくつかのクエリを試してみましたが、すべての学生を一覧表示する 1 つのクエリにたどり着くのは難しいと感じています。

4

4 に答える 4

1

これにより、コースに登録されているかどうかに関係なく、すべての学生が引き込まれます

SELECT s.student_id, student_name, count(c.course_id)
, sum(case when difficulty_level = 1 then 1 else 0 end) as level1
, sum(case when difficulty_level = 2 then 1 else 0 end) as level1
, sum(case when difficulty_level = 3 then 1 else 0 end) as level1
FROM students s 
  left outer join enrollment e ON s.student_id = e.student_id
  left outer join courses c ON e.course_id = c.course_id
GROUP BY s.student_id, student_name
于 2013-05-04T13:56:15.797 に答える
0
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)
from    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 by
        s.[Student ID]
,       s.[Student Name]
于 2013-05-04T13:56:15.360 に答える