如何在所有分支中获得第n个最高分?

时间:2012-12-14 04:50:55

标签: mysql sql

我有一个包含字段的学生:Student_idStudent_NameMarkBranch

我希望在单个查询中获得每个分支的第n个最高标记和名称。有可能吗?

例如,如果数据是

S1   |  Amir  |  EC  |  121
S2   |  Ewe   |  EC  |  123
S3   |  Haye  |  EC  |  45
S4   |  Mark  |  EC  |  145
S5   |  Tom   |  CS  |  152
S6   |  Hudd  |  CS  |  218
S7   |  Ken   |  CS  |  48
S8   |  Ben   |  CS  |  15
S9   |  Wode  |  CS  |  123
S10  |  Kayle |  IT  |  125
S11  |  Den   |  IT  |  120
S12  |  Noy   |  IT  |  126

我选择在每个分支中显示第三个最高标记,输出应该是

S1   | Amir   | EC   | 121
S9   | Wode   | CS   | 123
S11  | Den    | IT   | 120

5 个答案:

答案 0 :(得分:1)

如果MySQL有像其他几个答案所示的窗口函数,这将会容易得多。但它们并非如此,您可以使用以下内容:

select student_id,
      student_name,
      branch,
      mark
from
(
  select student_id,
      student_name,
      branch,
      mark,
      @num := if(@branch = `branch`, @num + 1, 1) as group_row_number,
      @branch := `branch` as dummy,
      overall_row_num
  from
  (
    select student_id,
      student_name,
      branch,
      mark,
      @rn:=@rn+1 overall_row_num
    from student, (SELECT @rn:=0) r
    order by convert(replace(student_id, 'S', ''), signed) 
  ) src
  order by branch, mark desc
) grp
where group_row_number = 3
order by overall_row_num

请参阅SQL Fiddle with Demo

结果将是:

| STUDENT_ID | STUDENT_NAME | BRANCH | MARK |
---------------------------------------------
|         S1 |         Amir |     EC |  121 |
|         S9 |         Wode |     CS |  123 |
|        S11 |          Den |     IT |  120 |

答案 1 :(得分:0)

MAX()

select branch, MAX(mark) as 'highest mark' from Student group by branch;

答案 2 :(得分:0)

MySQl不支持CTErownumber,因此您可以执行以下操作: - 创建一个临时表,将数据插入其中然后选择并最终删除临时表..

create table #temp(branch varchar(30),mark int,row_numbers int)
Insert into #temp
SELECT a.branch, a.mark, count(*) as row_numbers FROM student a
JOIN student b ON a.branch = b.branch AND a.mark <= b.mark
GROUP BY  a.mark,a.branch
Order by  a.mark desc

select branch,mark from #temp where row_numbers=2

drop table #temp 

这适用于SQL SERVER: -

;WITH CTE AS
(
SELECT  Branch,mark, ROW_NUMBER() OVER (PARTITION BY Branch ORDER BY mark DESC) AS RowNum
FROM 
student
)
SELECT Branch,mark from cte
WHERE RowNum = 2

这将给出第二个最高标记分支,你可以相应地选择任何第N个等级。

希望有所帮助: -

答案 3 :(得分:0)

这个在oracle中运行

select Student_id,Student_Name,Mark,Branch from (
    select  Student_id,Student_Name,Mark,Branch,dense_rank() over (partition by Branch order by Mark desc) rnk
    from Student ) where rnk=nth_value;

nth_value:=所需的第n个最高分。 请检查此sqlfiddle:http://sqlfiddle.com/#!4/7b559/3

答案 4 :(得分:-1)

您可以使用限制来获得最高市场(limit 1,1 will give you 2nd highest, set as per your requirement

SELECT mark, name
FROM student ORDER BY mark 
DESC LIMIT 1,1