对于以下格式的学生数据库
Roll Number | School Name | Name | Age | Gender | Class | Subject | Marks
如何找出每个班级最高的人?以下查询返回整个组,但我有兴趣找到组中的第一行。
select school,class,roll,sum(marks) as total from students group by school,class,roll order by school, class, total desc;
答案 0 :(得分:39)
select * from (
select *,
row_number() over (partition by school,class,roll order by marks desc) rn
from students
) t1 where rn = 1
如果您想返回所有领带以获得最高分,请使用rank()
代替row_number()
答案 1 :(得分:3)
您将再进行一次分组和联接以获得所需的结果。这应该做:
select q1.*, q2.roll from
(
select school, class, max(total) as max from
(
select school,class,roll,sum(marks) as total from students group by school,class,roll order by school, class, total desc
)q3 group by school, class
)q1
LEFT OUTER JOIN
(select school,class,roll,sum(marks) as total from students group by school,class,roll order by school, class, total desc)q2
ON (q1.max = q2.total) AND (q1.school = q2.school) AND (q1.class = q2.class)
答案 2 :(得分:0)
我们必须建立您提供的查询:
给定的查询将为您提供每卷每卷的标记。找出最高的 每个类实现的总数,您必须从select中删除滚动编号,然后在此查询中进行分组。
现在我们知道每所学校每班的学校,班级和最高总数。您只需要找出与此总数相对应的滚动编号。为此,需要加入。
最终查询将如下所示:
select a.school, a.class, b.roll, a.highest_marks from
(select q.school as school, q.class as class, max(q.total) as highest_marks from(select school, class, roll, sum(marks) as total from students group by school, class, roll)q group by school, class)a
join
(select school, class, roll, sum(marks) as total from students group by school, class, roll)b
on (a.school = b.school) and (a.class = b.class) and (a.highest_marks = b.total)