SQL查询问题

时间:2010-09-23 10:15:20

标签: sql-server

我有一个名为StudentMarks.的SQL表,它包含StudentID,SubjectName,SubjectMark

我想编写一个存储过程来为每个学生检索StudentID,TotalSubjectMarks,MarksAverage,ClassPosition。我需要从MarksAverage中找到ClassPosition。对于具有最高MarksAverage的学生,ClassPosition应为1.其他人应该获得2,3,4的位置.... 任何人都可以帮我这个???

谢谢。

3 个答案:

答案 0 :(得分:2)

  SELECT StudentID, TotalSubjectMark, MarksAverage,
  ROW_NUMBER() OVER (ORDER BY MarksAverage DESC) ClassPosition
  FROM (
    SELECT StudentID, 
    SUM(SubjectMark) TotalSubjectMark,
    AVG(SubjectMark) MarksAverage
    FROM StudentMarks sm
    GROUP BY StudentId
  )

答案 1 :(得分:1)

试试这个:

select * , ROW_NUMBER ()  OVER(ORDER BY avgmarks ) AS ClassPosition from
(
 select 
 studentid, sum(subjectmark) as total  , AVG(subjectmark)   as avgmarks
 from studentmarks  group by studentid
) d

答案 2 :(得分:1)

使用sql server 2005+,您可以尝试

DECLARE @StudentMarks TABLE(
        StudentID INT,
        SubjectName VARCHAR(50),
        SubjectMark FLOAT
)

INSERT INTO @StudentMarks SELECT 1, 'A', 80
INSERT INTO @StudentMarks SELECT 1, 'B', 80
INSERT INTO @StudentMarks SELECT 1, 'C', 80
INSERT INTO @StudentMarks SELECT 2, 'A', 60
INSERT INTO @StudentMarks SELECT 2, 'B', 60
INSERT INTO @StudentMarks SELECT 2, 'C', 60


;WITH Marks AS (
        SELECT  StudentID,
                SUM(SubjectMark) TotalSubjectMarks,
                AVG(SubjectMark) MarksAverage
        FROM    @StudentMarks
        GROUP BY StudentID
)
SELECT  *,
        ROW_NUMBER() OVER(ORDER BY MarksAverage DESC) Position
FROM    Marks