大數據技術之數倉--DW--Hadoop數倉實踐Case-17-累積度量

累積度量屬於半可加事實,使用的時候需要小心一些!

累計度量概述

  • 累積度量指的是聚合從序列內第一個元素到當前元素的數據, 例如統計從每年的一月到當前月份的累積銷售額。 本文說明如何在銷售訂單示例中實現累積月銷售數量和金額, 並對數據倉庫模式、 初始裝載、 定期裝載腳本做相應的修改。 累積度量是半可加的, 而且它的初始裝載比前面實現的要複雜。

數倉模型設計

  • 建立一個新的名爲month_end_balance_fact的事實表, 用來存儲銷售訂單金額和數量的月累積值。 month_end_balance_fact表在模式中構成了另一個星型模式。 新的星型模式除了包括這個新的事實表, 還包括兩個其他星型模式中已有的維度表, 即產品維度表與月份維度表。 下圖顯示了新的模式。 注意這裏只顯示了相關的表。

  • 【大數據開發學習資料領取方式】:加入大數據技術學習交流羣458345782,點擊加入羣聊,私信管理員即可免費領取

     

    累計度量數倉架構.PNG

創建表

  • 下面的腳本用於創建month_end_balance_fact表。
use dw;
create table
    month_end_balance_fact (
    month_sk int,
    product_sk int,
    month_end_amount_balance decimal(10,2),
    month_end_quantity_balance int
);

初始裝載

  • 現在要把month_end_sales_order_fact表裏的數據裝載進month_end_balance_fact表, 下面顯示了初始裝載month_end_balance_fact表的腳本。 此腳本裝載累積的月銷售訂單彙總數據, 從每年的一月累積到當月, 累積數據不跨年。
-- 初始化加載
use dw;
insert overwrite table
    month_end_balance_fact
select
a.month_sk,
b.product_sk,
sum(b.month_order_amount) month_order_amount,
sum(b.month_order_quantity) month_order_quantity
from
    month_dim a,
(select 
    a.*,
    b.year,
    b.month,
    max(a.order_month_sk) over () max_month_sk
from
    month_end_sales_order_fact a, month_dim b
where
    a.order_month_sk = b.month_sk) b
where
    a.month_sk <= b.max_month_sk
and
    a.year= b.year 
and b.month<= a.month
group by
    a.month_sk , b.product_sk;
  • 語句說明:子查詢獲取month_end_sales_order_fact表的數據, 及其年月和最大月份代理鍵。 外層查詢彙總每年一月到當月的累積銷售數據, a.month_sk <= b.max_month_sk條件用於限定只統計到現存的最大月份爲止。

定期裝載

  • 定期裝載銷售訂單累積度量, 每個月執行一次, 裝載上個月的數據。 可以在執行完月週期快照表定期裝載後執行該腳本。
-- 設置變量以支持事務
set hive.support.concurrency=true;
set hive.exec.dynamic.partition.mode=nonstrict;
set hive.txn.manager=org.apache.hadoop.hive.ql.lockmgr.dbtxnmanager;
set hive.compactor.initiator.on=true;
set hive.compactor.worker.threads=1;
use dw;
set hivevar:pre_month_date = add_months(current_date,-1);
set hivevar:year= year(${hivevar:pre_month_date});
set hivevar:month= month(${hivevar:pre_month_date});
insert into
    month_end_balance_fact
select
    order_month_sk,
    product_sk,
sum(month_order_amount),
sum(month_order_quantity)
from
(select
a.*
from
month_end_sales_order_fact a,
month_dim b
where
a.order_month_sk = b.month_sk
and
b.year= ${hivevar:year}
and
b.month= ${hivevar:month}
union all
select
month_sk + 1 order_month_sk,
product_sk product_sk,
month_end_amount_balance month_order_amount,
month_end_quantity_balance month_order_quantity
from
month_end_balance_fact a
wherea.month_sk in
(select max(case when${hivevar:month} = 1 then0 elsemonth_sk end
)
from
month_end_balance_fact)) t
group by
order_month_sk, product_sk
;
  • 週期加載腳本,需要進行驗證。


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章