Sql Server:按学生计算和分组标记

时间:2017-02-14 19:03:46

标签: sql-server

我有一张桌子;



<table><tbody><tr><th>StudentID</th><th>AcademicYear</th><th>Term</th><th>StudentName</th><th>Class</th><th>Marks</th><th>Position</th><th>Count</th></tr><tr><td>12013</td><td>2015</td><td>One</td><td>Adamu A. Msangi</td><td>Form IV</td><td>80</td><td>1</td><td>5</td></tr><tr><td>52013</td><td>2015</td><td>One</td><td>Angela M. Lucas</td><td>Form IV</td><td>67</td><td>2</td><td>5</td></tr><tr><td>22014</td><td>2014</td><td>Two</td><td>Agness Daudi Martin</td><td>Form II</td><td>60</td><td>3</td><td>5</td></tr><tr><td>32014</td><td>2014</td><td>Two</td><td>Agness John Missana</td><td>Form II</td><td>51</td><td>4</td><td>5</td></tr><tr><td>42013</td><td>2015</td><td>One</td><td>Andrea F. Agustino</td><td>Form IV</td><td>50</td><td>5</td><td>5</td></tr></tbody></table>
&#13;
&#13;
&#13;

我通过运行此SQL语句得到了:

SELECT 
    *,
    ROW_NUMBER() OVER (ORDER BY Marks DESC) AS Position,  
    COUNT(StudentID) OVER() AS 'Count'
FROM 
    Student

我要找的输出应该显示学生的位置和学生总数。例如,如果我查询ID为No的学生; 42013和Term =&#39; One&#39;和AcademicYear = 2015年和Class =&#39;表格IV&#39;,我应该得到与下表类似的结果:

&#13;
&#13;
<table><tbody><tr><th>StudentID</th><th>AcademicYear</th><th>Term</th><th>StudentName</th><th>Class</th><th>Marks</th><th>Position</th><th>Count</th></tr><tr><td>42013</td><td>2015</td><td>One</td><td>Andrea F. Agustino</td><td>Form IV</td><td>50</td><td>5</td><td>3</td></tr></tbody></table>
&#13;
&#13;
&#13;

这是我尝试过没有成功的事情;

SELECT 
    *,
    ROW_NUMBER() OVER (ORDER BY Marks DESC) AS Position,  
    COUNT(StudentID) OVER() AS 'Count'
FROM 
    Student 
WHERE 
    StudentID = 42013 
    AND Term = 'One' 
    AND AcademicYear = 2015 
    AND Class = 'Form IV' 

怎么办呢?

由于

1 个答案:

答案 0 :(得分:0)

您可以将查询放在子查询中,然后对其进行过滤: