2013-10-03 91 views
1

我有下面的代碼,我需要編寫子查詢來返回相同的結果。通過子查詢替換select into表

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 
+6

在*中,*字面意思*如果找不到解決方案,會有謀殺?並認爲我們抱怨休假時間和在各州的好處... – Yuck

+0

你有什麼問題? – enderland

+1

幾乎看起來像是不鼓勵/病態的動機 – billinkc

回答

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 
+0

我更喜歡你的答案,相同的概念,但更詳細。 –