查找和的最大值使用SQL服务器

时间:2013-10-03 11:10:36

标签: sql-server

我有这个查询我需要改变它以找到最大的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

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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