Hive的一個(gè)面試題

需求:求出每個(gè)User截止當(dāng)月總的流量

user date traffic
熊貓tv 2018-01-02 5
快手 2018-01-02 3
YY 2018-01-02 2
抖音 2018-01-02 15
熊貓tv 2018-01-03 5
快手 2018-01-03 3
YY 2018-01-03 2
抖音 2018-01-03 15
熊貓tv 2018-02-02 5
快手 2018-02-02 3
YY 2018-02-02 2
抖音 2018-02-02 15
熊貓tv 2018-02-03 5
快手 2018-02-03 3
YY 2018-02-03 2
抖音 2018-02-03 15
熊貓tv 2018-03-02 5
快手 2018-03-02 3
YY 2018-03-02 2
抖音 2018-03-02 15
熊貓tv 2018-03-03 5
快手 2018-03-03 3
YY 2018-03-03 2
抖音 2018-03-03 15

hive創(chuàng)建表:

create table user_traffic(user string,date string,traffic bigint) row format delimited fields terminated by '\t';

load data local inpath '/home/hadoop/data/user_traffic.txt' overwrite into table user_traffic;

先按user,月份分組求出每個(gè)月的traffic

select temp.user,temp.yearmonth,sum(temp.traffic) from(select 
user,concat(split(date,'-')[0],split(date,'-')[1]) as yearmonth,traffic 
from user_traffic) temp group by temp.user,temp.yearmonth;
image.png

表自連接

select t1.*,t2.* from (select temp.user,temp.yearmonth,sum(temp.traffic) from
 (select user,concat(split(date,'-')[0],split(date,'-')[1]) as yearmonth,traffic from user_traffic)
 temp group by temp.user,temp.yearmonth) t1,(select temp.user,temp.yearmonth,sum(temp.traffic) from
 (select user,concat(split(date,'-')[0],split(date,'-')[1]) as yearmonth,traffic from user_traffic) temp group by 
temp.user,temp.yearmonth) t2 where t1.yearmonth=t2.yearmonth and t1.user = t2.user and t1.yearmonth >= t2.yearmonth;
image.png

select t.user,t.yearmonth,sum(t.total) from (select t1.user,t1.yearmonth,t1.total from (select temp.user,temp.yearmonth,sum(temp.traffic) as total from (select user,concat(split(date,'-')[0],split(date,'-')[1]) as yearmonth,traffic from user_traffic) temp group by temp.user,temp.yearmonth) t1,(select temp.user,temp.yearmonth,sum(temp.traffic) as total from (select user,concat(split(date,'-')[0],split(date,'-')[1]) as yearmonth,traffic from user_traffic) temp group by temp.user,temp.yearmonth) t2 where t1.user = t2.user and t1.yearmonth >= t2.yearmonth) t group by t.user,t.yearmonth;

image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容