2010-09-23 135 views
1

我有一個名爲StudentMarks.which SQL表由StudentID,主旨名稱的,SubjectMarkSQL查詢問題

我想寫一個存儲過程來檢索StudentID,TotalSubjectMarks,MarksAverage,ClassPosition每個student.I需要找到MarksAverage的ClassPosition。對於具有最高MarksAverage的學生,ClassPosition應該是1.其他人應該得到的位置2,3,4 .... 任何人可以幫助我嗎?

謝謝。

+1

請編輯您的問題;增加以下幾點可能會給你更好的答案:1.你到目前爲止嘗試過什麼(這很重要,否則人們會認爲「做你自己的作業」並忽略這個問題)? 2.你得到了什麼結果? 3.這與你所期望的結果有何不同? – Piskvor 2010-09-23 10:20:23

回答

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

試試這個:

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