SQL server 2008,选择每个班级成绩最高的学生

时间:2016-11-08 07:48:53

标签: sql sql-server sql-server-2008

我有一个看起来像这样的数据库

+--------+-------+-------+
| ID     | Class | grade |
+--------+-------+-------+
| 123    |   A   | 100   |
| 2      |   B   | 84    |
| 357    |   A   | 46    |
| 43     |   B   | 12    |
| 55677  |   B   | 78    |
| 63432  |   A   | 63    |
+--------+-------+-------+
显然,我正在处理更大的数据库。 更多的学生,更多的课程 我想要达到的目标是选择两个班级成绩最高的学生。

所以,它应该显示:

+-------+-------+-------+
| ID    | Class | Grade |
+-------+-------+-------+
| 123   | A     | 100   |
| 63432 | A     | 63    |
| 2     | B     | 84    |
| 55677 | B     | 78    |
+-------+-------+-------+

我如何实现这一点谢谢!

我试过这个,但它给了我所有的行

select id, class, max(grade)
from school
group by id, class

++++

我还想对这个数据库做些什么。 我如何从每个班级中拉出前10%的学生? 在我添加了一个排名属性之后,我尝试在分组之后使用'having',如下所示:

rank < count(distinct ID) * 0.05

谢谢!

4 个答案:

答案 0 :(得分:2)

ROW_NUMBER()函数与partition by子句一起使用。

;WITH CTE AS (

SELECT id, Class, Grade,
       ROW_NUMBER() OVER(PARTITION BY Class ORDER BY Grade DESC) as rnk
FROM tableName
)

SELECT id, Class, Grade
FROM CTE
WHERE rnk <=2

答案 1 :(得分:0)

我认为 DENSE_RANK ROW_NUMBER 更好。

<强>查询

;with cte as(
    select [rank] = dense_rank() over(
        partition by [Class]
        order by [grade] desc
    ), *
    from [your_table_name]
)
select * from cte
where [rank] <= 2;

答案 2 :(得分:0)

试试这个:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainDiv">
  <div class="addrLabel">Address</div>
  <div class="addrValue">

    <!-- this content value i want to check if exist, then grab it else no value -->

    the content which i want to check if exist or not. if a single value is there i want to grab it also
    <span class="hrefClass">
      <a href="#">next link</a>
  </span>
  </div>
  <div class="clearfix"></div>
</div>

<div class="mainDiv">
  <div class="addrLabel">Address</div>
  <div class="addrValue">


    <span class="hrefClass">
      <a href="#">next link</a>
  </span>
  </div>
  <div class="clearfix"></div>
</div>

也会考虑多名同等成绩最高的学生。

答案 3 :(得分:0)

为此你需要使用group by和:

    select id,Class,Grade 
    from Student e 
    where Grade=(select max(Grade) 
    from Student w 
    group by w.Class having e.class=w.class)