-1

我有这个查询,我需要更改它以找到 Sum(StudentMark) 的最大值

SELECT  Users.UserID, 
        ClassCourses.CourseID,
        sum(StudentMark)SumOFMarks 
FROM    Users 
        INNER JOIN UserExams 
            ON Users.UserID = UserExams.UserID 
        INNER JOIN Exams 
            ON UserExams.ExamID = Exams.ExamID 
        INNER JOIN ClassCourses 
            ON Exams.ClassID = ClassCourses.ClassID 
            AND Exams.CourseID = ClassCourses.CourseID
GROUP BY Users.UserID, 
        ClassCourses.CourseID
4

2 回答 2

3

将其包装在 CTE 中并查询 CTE:

;WITH MyCTE AS
(
    SELECT  Users.UserID, 
            ClassCourses.CourseID,
            sum(StudentMark)SumOFMarks 
    FROM    Users 
            INNER JOIN UserExams 
                ON Users.UserID = UserExams.UserID 
            INNER JOIN Exams 
                ON UserExams.ExamID = Exams.ExamID 
            INNER JOIN ClassCourses 
                ON Exams.ClassID = ClassCourses.ClassID 
                AND Exams.CourseID = ClassCourses.CourseID
    GROUP BY Users.UserID, 
            ClassCourses.CourseID
)
SELECT MAX(SumOFMarks)
FROM   MyCTE 
于 2013-10-03T11:14:26.893 回答
0

这很好用

    Create procedure [dbo].[MaxMinMarks]
(
@pClassID int
)
as
--check if the table exists then if true delete it because we'll create it every time the SP run
IF  EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE 
                   TABLE_NAME = 'StudentMarks')
                 drop table StudentMarks
SELECT    ClassCourses.ClassID,ClassCourses.CourseID,ClassCourses.MaxMark,sum(StudentMark)SumOFMarks 
--store result into new table 
into StudentMarks
FROM         Users INNER JOIN
                      UserExams ON Users.UserID = UserExams.UserID INNER JOIN
                      Exams ON UserExams.ExamID = Exams.ExamID INNER JOIN
                      ClassCourses ON Exams.ClassID = ClassCourses.ClassID AND Exams.CourseID = ClassCourses.CourseID
                      where ClassCourses.ClassID=@pClassID
                     group by Users.UserID,  ClassCourses.ClassID,ClassCourses.CourseID,ClassCourses.MaxMark
--useing the new table we can find max and min marks
select ClassID,CourseID,MaxMark,max(SumOFMarks) highestMark,min(SumOFMarks)LowestMark from StudentMarks
group by ClassID,CourseID,MaxMark
于 2013-10-03T11:43:11.207 回答