使用Hive查找组中的第一行

Pra*_*ati 12 hive group-by hiveql

对于以下格式的学生数据库

Roll Number | School Name | Name | Age | Gender | Class | Subject | Marks
Run Code Online (Sandbox Code Playgroud)

如何找出每个班级最高的人?以下查询返回整个组,但我有兴趣找到组中的第一行.

select school,class,roll,sum(marks) as total from students group by school,class,roll order by school, class, total desc;
Run Code Online (Sandbox Code Playgroud)

Fuz*_*ree 44

另一种方式使用 row_number()

select * from (
    select *, 
    row_number() over (partition by school,class,roll order by marks desc) rn
    from students
) t1 where rn = 1
Run Code Online (Sandbox Code Playgroud)

如果你想返回所有领带的顶部标记,那么使用rank()而不是row_number()

  • 没有任何`first()`函数? (3认同)

Ama*_*mar 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)
Run Code Online (Sandbox Code Playgroud)