Hive中找出分組第一的記錄

使用group by進行分組查詢只能獲取分組列以及聚合函數列,如果想要獲取表中非分組列則獲取不到,此時可以使用row_number()對分組進行排序,同時也可以獲取非分組列。

表結構

學生課程分數表,三列

create table student_score
(
	student_id int, --學生id
	subject string, -- 課程
	score int		-- 分數
);

數據

insert into  student_score(student_id, subject, score) values
		(1, '語文’, 77),(1, '數學’, 80),(1, '英語’, 83),
		(2, '語文’, 81),(2, '數學’, 90),(2, '英語’, 95),
		(3, '語文’, 85),(3, '數學’, 83),(3, '英語’, 78),
		(4, '語文’, 75),(4, '數學’, 96),(4, '英語’, 81);

分組排序

找出每門課分數最高的學生及分數

select student_id, subject, score
from
(
	select student_id, subject, score,
    row_number() over(partition by subject order by score desc) as row_num
    from student_score
)tmp where row_num =1;

結果

3,'語文’,85
4,'數學’,96
2,'英語’,95
發佈了95 篇原創文章 · 獲贊 48 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章