hive lateral view函數簡介


函數簡介

lateral view 函數用於將數據一行轉多列,一般與explode、split、collect_set函數一起使用
基本使用

    案例A:現在有一張學生績效表,記錄了每個學生的所有科目的成績, 需要查詢所有拿了A的學生數

student_name(string)     student_course(array[])
stuA     [‘A’,‘B’,‘C’]
stuB     [‘A’,‘C’]
stuC     [‘B’,‘C’]



現在使用lateral view + explode函數對數據進行拆解,多行變一行

select student_name,course_value from student_course LATERRAL VIEW explode(student) tpTable AS course_v


拆解完成之后所得數據如下
student_name     course_value
stuA     ‘A’
stuA     ‘B’
stuA     ‘C’
stuB     ‘A’
stuB     ‘C’
stuC     ‘B’
stuC     ‘C’

接下來就可以進行聚合分析了:

select course_value,count(distinct student_name) as stu_num from course_single group by course_value where course_value='A'


結果:
course_value     stu_num
‘A’     2

    案例2:現有一張游戲表,知道2個字段,一個gameId:String, 另一個 tags:Array

 

 
現在需要把tags中的tag數組展開,即”一個gameID只能對應一個tag“
代碼

select t.gameId, singleTag
from (
    select gameId, tags from gamepublish.knights_game where date=20181127 limit 20
) t LATERAL VIEW explode(t.tags) v as singleTag

結果:
t.gameid     singletag
62245388     {“tagid”:1,“tagname”:“角色扮演”,“parent”:1}
62235467     {“tagid”:684,“tagname”:“3D”,“parent”:14}
62235467     {“tagid”:1128,“tagname”:“跨服”,“parent”:4110}
62235467     {“tagid”:443,“tagname”:“ARPG”,“parent”:1}
62235467     {“tagid”:1,“tagname”:“角色扮演”,“parent”:1}
62235467     {“tagid”:1066,“tagname”:“MMORPG”,“parent”:1}
62235467     {“tagid”:1006,“tagname”:“魔幻”,“parent”:16}
62232946     {“tagid”:683,“tagname”:“2D”,“parent”:14}
62232946     {“tagid”:534,“tagname”:“水墨風”,“parent”:14}
62232946     {“tagid”:1022,“tagname”:“中國風”,“parent”:14}
62232946     {“tagid”:1,“tagname”:“角色扮演”,“parent”:1}
62232946     {“tagid”:636,“tagname”:“冒險”,“parent”:2}
62232946     {“tagid”:2,“tagname”:“動作冒險”,“parent”:2}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM