1. 程式人生 > 其它 >hive的高階查詢練習

hive的高階查詢練習

技術標籤:hive大資料資料庫hadoop

一.每個店鋪top3(分組求topN)

題目:有50w個京東店鋪,每個顧客訪問任何一個店鋪的任何一個商品時,都會產生一條訪問日誌,訪問日誌儲存的表名為visit,訪客使用者id為user_id,被訪問的店鋪名稱為shop。
資料部分內容如下:
u1 a
u2 b
u1 b
u1 a
u3 c
u4 b
u1 a
u2 c
u5 b
u4 b
u6 c
u2 c
u1 a
u2 a
u2 a
u3 a
u5 a
需求:
1.每個店鋪UV(訪客數)去重

select shop, count( dsitinct user_id) from visit group
by shop

2.每個店鋪訪問次數top3的訪客資訊。輸出店鋪名、訪客id、訪問次數。
思路:先求出每個店鋪每個人的訪問量做表1->在對這個每個人訪問量的表1進行排名,求出每個店鋪每個人的訪問量的排名做表2->在對錶2的基礎繼續查詢,篩選出前三名即可。
第一步驟:求出每個店鋪每個人的訪問量做t1表

select shop, user_id, count(*) ct from visit group by shop,user_id

在這裡插入圖片描述
第二步驟:對表t1進行每個訪問量的排名做t2表

Select shop,user_id,ct,row_number() over(partition
by shop order by ct desc) as rk from (select shop, user_id, count(*) ct from visit group by shop,user_id) as t1

在這裡插入圖片描述
第三步驟:對t2表進行篩選出每個店鋪的前三名即可(where)

select shop, user_id, ct
 from 
 (select shop, user_id, ct, row_number() over(partition by shop order by ct desc) rk
  from
   (select shop, user_id, count
(*) ct from visit group by shop,user_id)t1 ) t2 where rk<=3;

在這裡插入圖片描述
分析執行結束。

二.求月銷售額和總銷售額

1、資料說明
(1)資料格式
a,01,150
a,01,200
b,01,1000
b,01,800
c,01,250
c,01,220
b,01,6000
a,02,2000
a,02,3000
b,02,1000
b,02,1500
c,02,350
c,02,280
a,03,350
a,03,250

(2)欄位含義
店鋪,月份,金額
3、需求
編寫Hive的HQL語句求出每個店鋪的當月銷售額
和累計到當月的總銷售額
程式碼如下:

with
r1 as
(
select
name,
months,
sum(money) money
from t_store
group by name,months
)
select
name,
months,
sum(money) over(partition by name,months order by months),
sum(money) over(partition by name order by months rows between unbounded preceding and current row)
from r1;

在這裡插入圖片描述