在SQL中获得流明智的最高标记

时间:2016-05-03 13:00:11

标签: sql oracle greatest-n-per-group

我有2张桌子

表1。 StudentMaster

      ROLL      CLASS NAME         TOTALMARKS   STREAMID
---------- ---------- ------------ ---------- ----------
 12345          5 Rohit                75        100
 12346          7 Suman                95        101
 12347          5 Rajib                41        100
 12348         10 Rakesh               52        102
 12349         10 Himesh                         101
 12350          7 Mizanur              85        103
 42145          5 Mohit                          103

表2。流

  STREAMID NAME         DURATION       FEES
---------- ---------- ---------- ----------
   100 electrical          3       4500
   102 civil               4       5400
   103 mechanical          3       4500
   101 ece                 2       2500

现在我需要了解每个流中得分最高的学生的详细信息。

输出表应如下所示:

Roll     Name       Stream         HighestMarks
----     -------    ------         ------------
12345    Rohit      electrical        75
12346    Suman      ece               95
12348    Rakesh     civil             52
12350    Mizanur    mechanical        85

你能帮我找到正确的Oracle SQL查询来检索这个吗?提前谢谢。

3 个答案:

答案 0 :(得分:0)

在mysql中,你需要一个带有order by的subselect来选择最高分

select a.ROLL as Roll, a.NAME as Name, b.NAME as Stream, a.TOTALMARKS  HighestMarks
from StudentMaster as a 
inner join Stream as b on b.STREAMID = a.STREAMID 
where a.rool in 
       (select rool from from StudentMaster 
           where (a.rool, STREAMID) in
             (select max(ROLL), STREAMID from StudentMaster 
        group by STREAMID))

答案 1 :(得分:0)

您可以使用:

SELECT *
  FROM (SELECT ROW_NUMBER() OVER(PARTITION BY STREAMID ORDER BY TOTALMARKS desc NULLS LAST) AS RANK,
               StudentMaster.name,
               stream.name AS stream,
               totalMarks AS HighestMarks
          FROM StudentMaster INNER JOIN STREAM USING (streamId))
 WHERE RANK = 1

它为连接表的每一行计算流中学生的等级,按标记排序;外部查询只是过滤以仅获取每个流的第一个位置的学生。 排序按降序进行,并且在最新位置使用NULL值

答案 2 :(得分:0)

我终于以最简单的方式解决了这个问题(我认为)

popstate