很抱歉在主題中寫了一個明顯錯誤的查詢,但它準確地描述了我正在尋找的結果。
我有一個帶有 classID int、studName string、grade int 的表。我需要一個列出在每門課程中取得最高成績的每個 classID、studName 的結果。多個學生可以達到該成績,每個學生應首先按 classID 降序排列,然后按 studName。
樣本輸出:| 類ID | 螺柱名| |---------|----------| | 101 | 瑪麗 | | 101 |內特 | | 101 |克里斯 | | 102 |本杰明| | 103 |內特 | |103 |湯姆 | ETC...
我的第一個猜測是:
SELECT classID, studName from table1 where grade = MAX(grade) group by classID, studName;
但這給出了一個錯誤: ... UDAF 'max' 的位置尚不支持
我也嘗試過創建一個視圖:
CREATE VIEW newView as select classID, MAX(grade) from table1 group by classID;
并在 where 陳述句的子查詢中使用它:
select classID, studName from table1 where grade IN (select * from newView) group by classID, studName;
但似乎:“子查詢只能包含 SELECT 串列中的一項”
我傾注了“Apache Hive Essentials”一書也沒有運氣。
我是 HiveQL 的新手,這個讓我徹夜難眠。任何幫助將不勝感激。
謝謝
uj5u.com熱心網友回復:
您的 SQL 存在問題 -
您需要命名最大列,然后在子查詢 IN 子句中使用它。
更改如下視??圖。
CREATE VIEW newView as select classID, MAX(grade) as maxgrade from table1 group by classID;
像這樣改變你的SQL
select classID, studName from table1 where grade IN (select maxgrade from newView) group by classID, studName;
解決方案 但是此 SQL 將幫助您通過調整您的 SQL 來實作您所需要的“找到在每個科目中獲得最高分的學生”。
select classID, studName, grade
from table1
join (select classID mxid, MAX(grade) as maxgrade from table1 group by classID) mx -- this subquery will pick maximum grade in each class.
ON grade =mx.maxgrade and classID = mx.mxid -- This join will select only the students with maximum grade in each class.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/460157.html
