1

我有以下代码,我需要编写子查询以返回相同的结果。

SELECT Users.UserID, 
       Users.FirstName,
       courses.CourseID,
       Count(Exams.examID)NumExams into CurrentExams
FROM ClassCourses 
INNER JOIN courses ON ClassCourses.CourseID = courses.CourseID 
INNER JOIN Exams ON ClassCourses.ClassID = Exams.ClassID 
                 AND ClassCourses.CourseID = Exams.CourseID 
INNER JOIN UserExams ON Exams.ExamID = UserExams.ExamID 
INNER JOIN Users ON UserExams.UserID = Users.UserID
group by Users.UserID, courses.CourseID, Users.FirstName

IF EXISTS (SELECT * 
           FROM INFORMATION_SCHEMA.TABLES 
           WHERE TABLE_NAME = 'AllExams')
    drop table AllExams               

SELECT courses.CourseID, count(ExamID) TotalExams into AllExams
FROM Exams 
INNER JOIN courses ON Exams.CourseID = courses.CourseID
group by Courses.CourseID

SELECT CurrentExams.FirstName, 
       CurrentExams.CourseID, 
       AllExams.TotalExams,
       AllExams.TotalExams-CurrentExams.NumExams AS Unlisted
FROM AllExams 
inner JOIN CurrentExams on CurrentExams.CourseID=AllExams.CourseID
4

1 回答 1

4

这是您需要的一个查询的简单版本。假设您有 sql server 2005 或更高版本。

  ;with CurrentExams as 
  (
     SELECT      Users.UserID, Users.FirstName,courses.CourseID,Count(Exams.examID)NumExams
     FROM         
        ClassCourses 
        INNER JOIN
                courses ON ClassCourses.CourseID = courses.CourseID INNER JOIN
                Exams ON ClassCourses.ClassID = Exams.ClassID AND ClassCourses.CourseID = Exams.CourseID INNER JOIN
                UserExams ON Exams.ExamID = UserExams.ExamID INNER JOIN
                Users ON UserExams.UserID = Users.UserID
     group by  Users.UserID,courses.CourseID, Users.FirstName
  ), 
  AllExams as
  (
     SELECT     courses.CourseID,count(ExamID) TotalExams
     FROM         
        Exams 
        INNER JOIN
                 courses ON Exams.CourseID = courses.CourseID
     group by Courses.CourseID
  )
  SELECT     CurrentExams.FirstName, CurrentExams.CourseID, AllExams.TotalExams,AllExams.TotalExams-CurrentExams.NumExams AS Unlisted
  FROM         
     AllExams 
     inner JOIN CurrentExams on CurrentExams.CourseID=AllExams.CourseID
于 2013-10-03T15:23:58.583 回答