棘手的统计选择

时间:2015-05-25 17:53:44

标签: sql sql-server

试图弄清楚这一段时间,但没有运气。我有以下表格(MS-SQL 2008): 的
studentID - email - profileID

课程
courseID - 名称

studentsCourses
studentID - courseID

简档
profileID - 名称

profilesMandatoryCourses
profileID - courseID

studentsCoursesLogs
logID - studentID -courseID - accessDate

每位学生在注册时都会被分配一份个人资料。每个档案都有一些必修课程。这些必修课程与用户参加的任何其他课程一起保存在studentsCourses表格中。

每当学生访问课程时,信息都会记录在studentsCoursesLogs中。

我试图找出所有根据他们的个人资料参加所有必修课程的学生。

任何指示赞赏。

1 个答案:

答案 0 :(得分:0)

我认为应该这样做(假设我已经正确理解了您的数据模型和要求 - 并且将这个示例SQL放在一起我没有犯任何错误 - 我没有在数据库中创建您的数据模型) 。我很确定它应该足够接近。

select studentRecords.StudentId, 
       sum(case TakenCourseID when null then 0 else 1 end) as CompleteMandatoryCourses,
       sum(case TakenCourseID when null then 1 else 0 end) as IncompleteMandatoryCourses
  from (
          select mandatoryCourses.StudentID, mandatoryCourses.CourseId as MandatoryCourseID, takenCourses.CourseID as TakenCourseID
            from ( -- Courses student should have taken - based on their profile
                   select p.[Profile], pmc.CourseID, s.StudentID 
                     from profiles p 
                     inner join profilesMandatoryCourses pmc on p.ProfileID = pmc.Profile
                     inner join students s on p.StudentID = s.StudentID
                 ) mandatoryCourses
            left join
                 (
                   -- Course students have taken
                   select s.StudentID, s.ProfileID, sc.CourseID
                     from students s
                     inner join studentsCourseLogs scl on s.StudentID = scl.StudentID
                 ) takenCourses on mandatoryCourses.ProfileId = takenCourses.ProfileID
                               and mandatoryCourses.CourseID = takenCourses.CourseID
       ) studentRecords
group by mandatoryCourse.StudentId
having sum(case TakenCourseID when null then 1 else 0 end) = 0

它将提供如下记录集....

 +----------------+-----------------------------+-------------------------------+
 |  StudentID     |  CompleteMandatoryCourses   |  IncompleteMandatoryCourses   |
 +----------------+-----------------------------+-------------------------------+
 |      1         |      15                     |        3                      |
 |      2         |       8                     |        0                      |
 +----------------+-----------------------------+-------------------------------+

如果您只想要一份已经参加过所有必修课程的学生名单,您可以将以上所有内容包括在内,如图所示......

select studentID 
  from ( /* insert very long sql here */ ) 
 where IncompleteMandatoryCourses = 0`